Canvas redraws only after loop ends

孤人 提交于 2019-12-19 08:56:08

问题


I have an issue with drawing on canvas in a loop.

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.

What it does instead is that the user can't see the change, until the for-loop ends.

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.

How to show "the small changes" in every loop, not just in the end?

My code (also here: http://janiczek.github.com/heighway-dragon/ the 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>

回答1:


Use setTimeout instead of your sleep function to release the UI thread temporarily. Note that setTimeout sets the minimum delay, the function passed into it could be delayed longer if something that executes before the function is scheduled to be called takes longer than the delay you passed into setTimeout.

E.g. replace your for loop with the following:

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();


来源:https://stackoverflow.com/questions/4523342/canvas-redraws-only-after-loop-ends

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!