这是我的代码。我在 Canvas 上创建了一个 VIBGOYR 图案,并希望在一段时间间隔后更改系统的径向渐变,使其看起来具有动画效果。
function activate(index){
canvas =document.getElementById("exp");
context = canvas.getContext('2d');
//Start.
draw(index);
//Functions.
function draw(index){
drawGradiantSq(index);
var t=setTimeout(doTimer,1000);
}
function doTimer(){
draw(index+10);
}
function drawGradiantSq(fi){
console.log(fi);
var g1 = context.createRadialGradient(0,300,0,500,300,fi);
colors = ["violet","indigo","blue","green","orange","yellow","red"];
var x= 1/12;
for (var i=0;i<colors.length;i++){
g1.addColorStop(i*x,colors[i]);
}
context.fillStyle = g1;
context.fillRect(0,0,500,600);
var g2 = context.createRadialGradient(1000,300,0,500,300,fi);
for (var i=0;i<colors.length;i++){
g2.addColorStop(i*x,colors[i]);
}
context.fillStyle = g2;
context.fillRect(500,0,1000,600);
}
}
但我得到的输出只改变梯度一次,尽管计时器似乎工作正常。
HTML 文件:
<body>
<canvas id="exp" width="1000px" height="600px"></canvas>
<button onclick="activate(index+=10);">Paint</button>
</body>
变量索引是一个全局变量,设置为0。
最佳答案
尝试使用setInterval
而不是setTimeout
。
setTimeout
仅触发一次:
'setInterval' vs 'setTimeout'
关于javascript - setTimeout() 和 Canvas 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9359332/