setTimeout()和画布不能按预期工作
这是我的代码。我在画布上创建了一个VIBGOYR模式,并希望在一段时间间隔后更改系统的径向渐变,以使其看起来具有动画效果。
setTimeout()和画布不能按预期工作
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'
为什么从你是谁的downvote?这是一个有效的答案。 – 2012-02-20 10:29:50
回调'doTimer'调用'draw',再次调用'setTimeout'。 – Leonid 2012-02-20 10:49:15
啊对了,道歉。我没有看到递归。 但有趣的是,它被标记为答案。 – 2012-02-20 10:54:02
指数保持不变,尝试'函数doTimer(){画(指数+ = 10);}' – Leonid 2012-02-20 10:38:54