Canvas redraws only after loop ends

后端 未结 1 2014
刺人心
刺人心 2021-01-14 01:59

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 us

相关标签:
1条回答
  • 2021-01-14 02:31

    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();
    
    0 讨论(0)
提交回复
热议问题