简体   繁体   English

线条的jCanvas延迟绘制

[英]Delayed jCanvas drawing of a line

I have already tried my luck and searched a lot but could not find a solution to my issue. 我已经尝试过运气,进行了很多搜索,但找不到解决我问题的方法。 The function in question is supposed to draw a set of lines using jcanvas and pause the drawing according to prerecorded times. 该函数应该使用jcanvas绘制一组线,并根据预先记录的时间暂停绘制。 Instead it just draws the entire lines at once. 相反,它只是一次绘制整条线。 Here is the jQuery code in question: 这是有问题的jQuery代码:

$("#start").click(function(){
        $("canvas").css("display","block"); 
        var obj = {  strokeStyle: "#000",  strokeWidth: 6,  rounded: true};
        for (i=0;i<counter;i++)
        {
            obj['x'+(i+1)] = arrX[i]; 
            obj['y'+(i+1)] = arrY[i] - 12; 
            setTimeout(function() {
                var interval = setInterval(function() {
                    $("canvas").drawLine(obj);
                }, 0);

            }, timeDiffs[i]);                               
        }
});

Because the loop finishes before your setTimeout() callback is run, your callback will always reference the final state of the object (that is, its state after the entire loop has run). 因为循环在您的setTimeout()回调运行之前完成,所以您的回调将始终引用对象的最终状态(即,在整个循环运行之后的状态)。

To fix this, you can wrap your setTimeout() callback in a closure. 要解决此问题,您可以将setTimeout()回调包装在闭包中。 By wrapping the callback in a closure function, I am capturing the state of the obj variable. 通过将回调包装在闭包函数中,我正在捕获obj变量的状态。 However, in this case, because objects are passes by reference in JavaScript, I have cloned the object (using $.extend ) to ensure that its current state (properties and all) is preserved. 但是,在这种情况下,因为对象是通过JavaScript中的引用传递的,所以我克隆了该对象(使用$.extend )以确保保留其当前状态(属性和所有状态)。

setTimeout((function(obj) {
    return function() {
        var interval = setInterval(function() {
            $("canvas").drawLine(obj);
        }, 0);
    };
}($.extend({}, obj))), timeDiffs[i]);

FWIW, there is an extensive examination of this issue on StackOverflow . FWIW, 在StackOverflow上对此问题进行了广泛的研究

just a simplification of Caleb531's point 只是Caleb531观点的简化

$("#start").click(function(){

    $("canvas").css("display","block"); 
    var obj = {  strokeStyle: "#000",  strokeWidth: 6,  rounded: true};
    for (i=0;i<counter;i++)
    {
      (function(){
        obj['x'+(i+1)] = arrX[i]; 
        obj['y'+(i+1)] = arrY[i] - 12; 

        var incremental = $.extend({}, obj);

        setTimeout(function() {
            var interval = setInterval(function() {
                $("canvas").drawLine(incremental);
            }, 0);

        }, timeDiffs[i]);      
      })();                         
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM