setTimeout() 和画布未按预期工作
这是我的代码。我在画布上创建了一个 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 的全局变量。
Here's my code. I created a VIBGOYR pattern on the canvas and want to change the radial gradient of the system after a time interval so that it looks animated.
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);
}
}
But the output i'm getting only changes the gradient only once although the timer seems to be working fine.
The HTML file:
<body>
<canvas id="exp" width="1000px" height="600px"></canvas>
<button onclick="activate(index+=10);">Paint</button>
</body>
The variable index is a global variable set to 0.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
更多
发布评论
评论(1)
尝试使用
setInterval
而不是setTimeout
。setTimeout
仅触发一次:“setInterval”与“setTimeout”
Try using
setInterval
instead ofsetTimeout
.setTimeout
is only triggered once:'setInterval' vs 'setTimeout'