动画无法在多个动态添加的画布上工作。
我正在尝试在同一页面上动态添加多个画布,并希望为每个画布中的对象分别设置动画。
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/
动画仅在最后一个画布上起作用。我希望动画能在所有画布上正常工作。
答案 0 :(得分:3)
我认为您遇到了循环范围问题。
您可以在文章here或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;
}