0
我想讓我的程序創建一個縮小的圓,直到它消失。圓圈應該在改變顏色的同時在無限循環中完成此操作(從起始顏色到結束顏色)。圓形工作正常,但爲了使顏色效果我改變了我的代碼,現在它只做了幾次,而真正快速地改變顏色,然後動畫消失,我不明白爲什麼。代碼是未完成的,但我需要幫助才能知道爲什麼它不能改變顏色,同時動畫的圓圈。下面是最近代碼:JavaScript使用requestAnimationFrame來定義大小和顏色
<script>
var mainCanvas = document.getElementById("myCanvas");
var mainContext = mainCanvas.getContext('2d');
var canvasWidth = mainCanvas.width;
var canvasHeight = mainCanvas.height;
var angle = 0;
var color='#006699';
//var colorend='#000000';
var steps=100;
var requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
function main(){
var interval = setInterval(function() {
drawCircle();
changeColor();
}, 10);//if i change to a larger value the animation dosen't show
}
function changeColor(){
var hexc = color.substring(1);
var decimalc = parseInt(hexc, 16);
decimalc=decimalc-steps;
hexc = decimalc.toString(16);
color= '#'.concat(hexc);
mainContext.fillStyle = color;
mainContext.fill();
}
function drawCircle() {
mainContext.clearRect(0, 0, canvasWidth, canvasHeight);
// color in the background
mainContext.fillStyle = "#EEEEEE";
mainContext.fillRect(0, 0, canvasWidth, canvasHeight);
// draw the circle
mainContext.beginPath();
var radius = 10 * Math.abs(Math.cos(angle));
mainContext.arc(225, 225, radius, 0, Math.PI * 2, false);
mainContext.closePath();
// color in the circle
mainContext.fillStyle = color;
mainContext.fill();
angle += Math.PI/40;
if(radius<=0.1){
return;//exit animation
}
requestAnimationFrame(drawCircle);
}
main();
</script>