paperjs:动画不适用于所有动态添加的 canvas

paperjs: animation not working on all dynamically added canvas

动画无法处理多个动态添加的 canvas。

我正在尝试在同一页面上动态添加多个 canvas,并希望在每个 canvas.

中分别为对象设置动画

HTML代码

input id="genCan" type="button" value="Generate" style="width:100px"

Javascript代码

document.getElementById('genCan').onclick = genCanvas;

function genCanvas() {
    var scope = [];
    var bodyEle = document.getElementsByTagName('body');

    for(var i=0; i < 2; i++) {
        var canvasEle = document.createElement('canvas');
        canvasEle.id = "canvas" + i;
        canvasEle.width = 150;
        canvasEle.height = 150;
        canvasEle.style.border = "1px solid black";
        bodyEle[0].appendChild(canvasEle);
    }

    for(var i=0; i < 2; i++) {
        var id = 'canvas' + i;
        scope[i] = new paper.PaperScope();

        //paper = scope[i];
        scope[i].setup(document.getElementById(id));
        //scope[i].activate();

        var circle = new scope[i].Path.Circle(scope[i].view.center, 50);
        circle.fillColor = 'red';
        scope[i].view.onFrame = function(event) {
            var delay = event.count % 60;
            if(delay < 30) {
                circle.fillColor = 'red';
            } else {
                circle.fillColor = 'blue';
            }
        }
        scope[i].view.draw();
    }

    document.getElementById('genCan').disabled = true;
}

https://jsfiddle.net/46zjgo91/2/

动画仅在最后一个 canvas 上运行。我期待动画适用于所有 canvas.

我认为您遇到了循环范围问题。
您可以在文章 here or here 或 Google.
上的其他地方找到关于此的信息和解决方法 一个简单的解决方案可能是将循环代码包装在 IIFE.

这里是 fiddle 演示解决方案。

document.getElementById('genCan').onclick = genCanvas;

function genCanvas() {
    var scope = [];
    var bodyEle = document.getElementsByTagName('body');

    for (var i = 0; i < 2; i++) {
        var canvasEle = document.createElement('canvas');
        canvasEle.id = 'canvas' + i;
        canvasEle.width = 150;
        canvasEle.height = 150;
        canvasEle.style.border = '1px solid black';
        bodyEle[0].appendChild(canvasEle);
    }

    for (var i = 0; i < 2; i++) {
        (function() {
            var id = 'canvas' + i;
            scope[i] = new paper.PaperScope();

            //paper = scope[i];
            scope[i].setup(document.getElementById(id));
            //scope[i].activate();

            var circle = new scope[i].Path.Circle(scope[i].view.center, 50);
            circle.fillColor = 'red';
            scope[i].view.onFrame = function(event) {
                var delay = event.count % 60;
                if (delay < 30) {
                    circle.fillColor = 'red';
                } else {
                    circle.fillColor = 'blue';
                }
            };
            scope[i].view.draw();
        })();
    }

    document.getElementById('genCan').disabled = true;
}