I have a problem with drawing on canvas in a loop.
What I want to achieve is that in each cycle the script waits for a few milliseconds, then draws on the canvas, the user can see this change, and then the cycle repeats.
Instead, it does so that the user cannot see this change until the for-loop loop completes.
But I found that if I show a warning window and the script is waiting for a user response, it actually draws a change.
How to show "small changes" in each cycle, and not just at the end?
My code ( also here: http://janiczek.github.com/heighway-dragon/ link now contains something else):
<script type="text/javascript"> function sleep (ms) { var start = new Date().getTime(); while (new Date().getTime() < 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 < 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); } }; </script> <canvas id=canvas width=300 height=300 style="border: 2px solid #000"></canvas><br> <input type="submit" value="Without alert" onclick="draw()"> <input type="submit" value="With alert" onclick="draw(true)"> <script type="text/javascript"> var canvas = document.getElementById("canvas"); var c = canvas.getContext("2d"); </script>
source share