The canvas is redrawn only after the cycle is completed

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> 
+4
source share
1 answer

Use setTimeout instead of your sleep function to temporarily free up the user interface thread. Please note that setTimeout sets the minimum delay; the function passed to it may be delayed longer if something that is executed before the function is called takes longer than the delay you passed to setTimeout .

eg. replace the for loop as follows:

 var count = 0; var drawPortion = function() { c.beginPath(); c.moveTo(cur_x, cur_y); cur_x += length; c.lineTo(cur_x, cur_y); c.stroke(); count++; if(count < steps) { setTimeout(drawPortion, 100); } }; drawPortion(); 
+4
source

Source: https://habr.com/ru/post/1333249/


All Articles