2017-06-20 67 views
3

我已經嘗試了一些代碼,但它不能正常工作。如何設置循環的時間延遲,每當它執行時,在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>
它顯示5秒後的完整產品線,但我需要一個每5秒顯示一個線的一部分。

回答

1

在這裏你去

\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>

+0

是完美的答案!!! ..其清晰,我需要做一個小的改變..謝謝你@Dummy –

1

您需要在設置的超時時間內包裝設置的時間間隔。在下面的代碼中,您可以根據需要更改時間間隔。

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 –