画布仅在循环结束后才重画 [英] Canvas redraws only after loop ends

查看:89
本文介绍了画布仅在循环结束后才重画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在循环在画布上绘画时遇到问题.

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.

它的作用是,直到for循环结束,用户才能看到更改.

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?

我的代码(也可以在这里: http://janiczek.github.com/heighway- dragon/ 链接现在包含其他内容):

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>

推荐答案

使用setTimeout代替您的sleep函数临时释放UI线程.请注意,setTimeout设置了最小延迟,如果在计划调用该函数之前执行的某些操作所花费的时间比传递给setTimeout的延迟长,则传递给它的函数可能会延迟更长的时间.

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.

例如将for循环替换为以下内容:

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

这篇关于画布仅在循环结束后才重画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆