Javascript setTimeout()和画布未按预期工作
这是我的密码。我在画布上创建了一个VIBGOYR图案,并希望在一段时间间隔后更改系统的径向渐变,使其看起来像动画Javascript setTimeout()和画布未按预期工作,javascript,html,canvas,Javascript,Html,Canvas,这是我的密码。我在画布上创建了一个VIBGOYR图案,并希望在一段时间间隔后更改系统的径向渐变,使其看起来像动画 function activate(index){ canvas =document.getElementById("exp"); context = canvas.getContext('2d'); //Start. draw(index); //Functions. function draw(index){ drawGradiantS
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);
}
}
功能激活(索引){
canvas=document.getElementById(“exp”);
context=canvas.getContext('2d');
//开始。
绘制(索引);
//功能。
功能图(索引){
drawGradiantSq(索引);
var t=设置超时(doTimer,1000);
}
函数doTimer(){
抽签(指数+10);
}
函数drawGradiantSq(fi){
控制台日志(fi);
var g1=context.createRadialGradient(0300,050300,fi);
颜色=[“紫色”、“靛蓝”、“蓝色”、“绿色”、“橙色”、“黄色”、“红色”];
var x=1/12;
对于(var i=0;i尝试使用setInterval
而不是setTimeout
setTimeout
仅触发一次:
为什么不管你是谁都投反对票?这是一个有效的答案。回调的doTimer
调用draw
再次调用setTimeout
。啊,对了,抱歉。我没有看到递归。有趣的是,它被标记为答案。不过,index保持不变,请尝试函数doTimer(){draw(index+=10);}
<body>
<canvas id="exp" width="1000px" height="600px"></canvas>
<button onclick="activate(index+=10);">Paint</button>
</body>