我使用 mootools 和 mootools Canvas 库编写了以下代码。
CANVAS.init({ canvasElement : 'canvas', interactive : true });
var itemlayer = CANVAS.layers.add({ id : 'items' });
for(var j = 0; j < 5; j++)
{
for(var i = 0; i < 5; i++)
{
itemlayer.add({
id : 'item-'+i + '-' + j,
x : 51 * i,
y : 51 * j,
w : 50,
h : 50,
state : 'normal',
interactive : true, //although they have no interactive events!
colors : { normal : '#f00', hover : '#00f' },
events : {
onDraw : function(ctx){
ctx.fillStyle = this.colors[this.state];
ctx.fillRect(this.x,this.y,this.w,this.h);
this.setDims(this.x,this.y,this.w,this.h);
}
}
});
}
}
CANVAS.addThread(new Thread({
id : 'myThread',
onExec : function(){
CANVAS.clear().draw();
}
}));
现在我想做的是在 Canvas 上绘制方 block 后立即销毁它们。
文档中给出的函数是
item.destroy( );
问题是,无论我怎么做,我都无法销毁 Canvas 上的对象!正确的做法是什么?
最佳答案
Mootools 是一个基于类的 JavaScript 框架。为了使用它,您需要像调用类一样调用对象,而不是直接调用它们的构造函数。
CANVAS 库是一个异常(exception),因为它是一个“静态”类。但是,在使用图层方法之前,您需要初始化图层类。
当您使用 Layer 类的 add 方法时,您要求将新项目添加到该 Layer 类中。您可以使用此方法两次,一次在循环之前,一次在循环内部。但是,您永远不会初始化图层类。因此,我假设循环之前的情况应该初始化类。这需要替换为 var itemlayer = new Layer('items');
当在循环内使用itemlayer.add
时,您将传递并对象到Layer对象,然后该对象会自动为您创建CanvasItem对象。然后它将这些对象返回给您。由于 destroy 方法是 CanvasItem 类的成员,因此您需要将它们捕获在变量中才能调用它。由于它发生在循环内,如果您想删除循环外的对象,您将需要一个数组。
CANVAS.init({ canvasElement : 'canvas', interactive : true });
var itemlayer = new Layer('items');
var itemArray = new Array;
for(var j = 0; j < 5; j++)
{
for(var i = 0; i < 5; i++)
{
item Array[j][i] = itemlayer.add({
id : 'item-'+i + '-' + j,
x : 51 * i,
y : 51 * j,
w : 50,
h : 50,
state : 'normal',
interactive : true, //although they have no interactive events!
colors : { normal : '#f00', hover : '#00f' },
events : {
onDraw : function(ctx){
ctx.fillStyle = this.colors[this.state];
ctx.fillRect(this.x,this.y,this.w,this.h);
this.setDims(this.x,this.y,this.w,this.h);
}
}
});
}
那么当你想销毁一个item时,只要知道它的j和i索引,就可以使用itemArray[j][i].destroy()
删除它。
最后,请记住,destroy 方法仅记录为触发 CanvasItem 的 destroy 事件。根据库的实现,您可能需要编写自己的销毁事件才能实际将其从 Canvas 中删除。
关于javascript - 需要帮助使用此函数来使用 javascript 销毁 Canvas 上的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3748941/