我/是否可以枚举已添加到 Canvas 元素的所有对象,并迭代它们?
顺便说一句 - jCanvas 可用。
最佳答案
Canvas 只是一个位图,不使用对象 - 仅在光栅化已定义的形状后使用像素。
但是,您可以创建自己的对象来表示正在绘制到 Canvas 上的内容,并将这些对象存储在数组中。通过这种方式,您可以迭代、更改和重新绘制 Canvas 对象(如果需要,甚至可以将它们导出为 SVG、PDF、XML、JSON 等)。
对象可以很简单:
function Rect(x, y, w, h) {
this.x = x;
this.y = y;
this.width = w;
this.height = h;
// example render
this.render = function(ctx) {
ctx.beginPath();
ctx.rect(this.x, this.y, this.width, this.height);
ctx.stroke();
}
}
然后分配它:
var shapes = [];
shapes.push(new Rect(10, 10, 200, 200));
shapes.push(new Rect(50, 50, 100, 150));
迭代时,您可以渲染它们、更改它们等等:
for(var i = 0, shape; shape = shapes[i++];) {
shape.render(ctx); // render this shape
shape.x += 5; // move 5 pixels to right
}
当然,这里进行了简化并没有优化,但您应该明白了。
关于javascript - HTML5 Canvas : How to enumerate all objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22547682/