我正在尝试回顾我学到的东西,并打算只制作一个圆形颜色渐变动画,这个错误仍然会一如既往地出现,这有点让我感到困惑。脚本如下:
canvas = document.getElementById('myCanvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
console.log(canvas.width,canvas.height);
ctx = canvas.getContext('2d');
function drawCircle(x,y,r){
ctx.clearRect(0,0,canvas.height,canvas.width);
requestAnimationFrame(drawCircle);
var grad = ctx.createRadialGradient(x,y,0,x,y,r);
var colorArray = ['blue','yellow','green','red','grey'];
grad.addColorStop(0,colorArray[Math.floor(Math.random()*colorArray.length)]);
grad.addColorStop(.3,colorArray[Math.floor(Math.random()*colorArray.length)]);
grad.addColorStop(.5,colorArray[Math.floor(Math.random()*colorArray.length)]);
grad.addColorStop(.6,colorArray[Math.floor(Math.random()*colorArray.length)]);
grad.addColorStop(.9,colorArray[Math.floor(Math.random()*colorArray.length)]);
ctx.beginPath();
ctx.arc(x,y,r,0,Math.PI*2);
ctx.fillStyle = grad;
ctx.fill();
}
drawCircle(100,100,20);
有人可以帮我查一下吗?
答案 0 :(得分:0)
发生错误是因为,在通过 requestAnimationFrame 调用drawCircle
函数时,您没有传递参数(x,y,r)。
因此,要解决此问题,您需要调用该函数,如此...
requestAnimationFrame(function() {
drawCircle(x, y, r);
});
canvas = document.getElementById('myCanvas');
ctx = canvas.getContext('2d');
canvas.width = 200;
canvas.height = 200;
function drawCircle(x, y, r) {
ctx.clearRect(0, 0, canvas.height, canvas.width);
var grad = ctx.createRadialGradient(x, y, 0, x, y, r);
var colorArray = ['blue', 'yellow', 'green', 'red', 'grey'];
grad.addColorStop(0, colorArray[Math.floor(Math.random() * colorArray.length)]);
grad.addColorStop(0.3, colorArray[Math.floor(Math.random() * colorArray.length)]);
grad.addColorStop(0.5, colorArray[Math.floor(Math.random() * colorArray.length)]);
grad.addColorStop(0.6, colorArray[Math.floor(Math.random() * colorArray.length)]);
grad.addColorStop(0.9, colorArray[Math.floor(Math.random() * colorArray.length)]);
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI * 2);
ctx.fillStyle = grad;
ctx.fill();
requestAnimationFrame(function() {
drawCircle(x, y, r);
});
}
drawCircle(100, 100, 20);
body{overflow:hidden}canvas {border: 1px solid #ccc;}
<canvas id="myCanvas"></canvas>