Note that there are some explanatory texts on larger screens.

plurals
  1. POCanvas redraws only after loop ends
    primarykey
    data
    text
    <p>I have an issue with drawing on canvas in a loop.</p> <p>What I want to achieve is that in each loop the script waits for a few milliseconds, then draws on a canvas, the user can actually see the change, and then the loop repeats.</p> <p>What it does instead is that the user can't see the change, until the for-loop ends.</p> <p>But I have found that if I show an alert window and the script waits for the user to respond, it actually draws the change.</p> <p>How to show "the small changes" in every loop, not just in the end?</p> <p>My code (<s>also here: <a href="http://janiczek.github.com/heighway-dragon/" rel="nofollow">http://janiczek.github.com/heighway-dragon/</a> </s> the link now contains something else):</p> <pre><code>&lt;script type="text/javascript"&gt; function sleep (ms) { var start = new Date().getTime(); while (new Date().getTime() &lt; start + ms) continue; }; function draw (withalert) { if (withalert == null) withalert = false; var cur_x = 100 - .5; var cur_y = 200 - .5; length = 3; steps = 20; c.strokeStyle = "#f00"; canvas.width = canvas.width; for (var count = 0; count &lt; steps; count++) { sleep(100); c.beginPath(); c.moveTo(cur_x, cur_y); cur_x += length; c.lineTo(cur_x, cur_y); c.stroke(); if (withalert) alert(count); } }; &lt;/script&gt; &lt;canvas id=canvas width=300 height=300 style="border: 2px solid #000"&gt;&lt;/canvas&gt;&lt;br&gt; &lt;input type="submit" value="Without alert" onclick="draw()"&gt; &lt;input type="submit" value="With alert" onclick="draw(true)"&gt; &lt;script type="text/javascript"&gt; var canvas = document.getElementById("canvas"); var c = canvas.getContext("2d"); &lt;/script&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload