如何设置循环的时间延迟,每当它执行时,在Javascript中
问题描述:
我已经尝试了一些代码,但它不能正常工作。如何设置循环的时间延迟,每当它执行时,在Javascript中
\t \t var canvas=document.getElementById('can');
\t \t ctx=canvas.getContext('2d');
\t \t canvas.width=1200;
\t \t canvas.height=750;
\t \t
\t \t for (var x = 100; x <=900; x+=10) {
\t \t \t \t linedraw(x);
\t \t }
\t \t function linedraw(n) {
\t \t \t setTimeout(function(){
\t \t \t \t ctx.moveTo(n,100);
\t \t \t \t ctx.lineTo(n+20,100); \t
\t \t \t \t ctx.stroke();
\t \t \t },1000 * 5);
\t \t }
<canvas id="can" style="background-color: gray"></canvas>
答
在这里你去
\t \t var canvas=document.getElementById('can');
\t \t ctx=canvas.getContext('2d');
\t \t canvas.width=1200;
\t \t canvas.height=750;
\t \t
\t \t for (var x = 100; x <=900; x+=10) {
\t \t \t \t linedraw(x);
\t \t }
\t \t function linedraw(n) {
\t \t \t setTimeout(function(){
\t \t \t \t ctx.moveTo(n,100);
\t \t \t \t ctx.lineTo(n+20,100); \t
\t \t \t \t ctx.stroke();
\t \t \t },5000/900*n); // change here
\t \t }
<canvas id="can" style="background-color: gray"></canvas>
答
您需要在设置的超时时间内包装设置的时间间隔。在下面的代码中,您可以根据需要更改时间间隔。
JS:
var canvas = $("#myCanvas")[0];
var c = canvas.getContext("2d");
var amount = 0;
var startX = 164;
var startY = 120;
var endX = 1094;
var endY = 120;
setTimeout(function() {
setInterval(function() {
amount += 0.01; // change to alter duration
if (amount > 1) amount = 1;
c.clearRect(0, 0, canvas.width, canvas.height);
c.strokeStyle = "black";
c.lineWidth=1;
c.strokeStyle="#707070";
c.moveTo(startX, startY);
// lerp : a + (b - a) * f
c.lineTo(startX + (endX - startX) * amount, startY + (endY - startY) * amount);
c.stroke();
}, 100);
}, 0);
HTML:
<canvas id="myCanvas" width="1250" height="120"></canvas>
+0
是的,你的答案是正确的..但我想这与...发生for循环..你可以请尝试.. @selvassn –
是完美的答案!!! ..其清晰,我需要做一个小的改变..谢谢你@Dummy –