0

我正在使用 KineticJS,但是当我尝试在舞台上的一个图层上删除两个组件(一个 Kinetic.Image 实例和一个 Kinetic.Text 实例)时,我得到了未捕获的类型错误,即使我已经将我的代码放在了 try catch 块中.

是什么导致了错误?

这是相关代码

var arr = myStage.getChildren()[1].get(".sceneComponents");

for (var i =0; i<arr.length; i++)
{
    try
    {
        //arr[i].setVisible(false);   // Setting its visibility to false works absolutely fine
        arr[i].remove();  //Trying to remove like this throws the uncaught error
    }
    catch(ex)
    {
        console.log(ex);
    }
}

这是完整的错误日志。

Uncaught TypeError: Cannot call method 'getLayer' of undefined kinetic.js:37
Kinetic.Node.getLayer kinetic.js:37
Kinetic.Shape.drawHit kinetic.js:42
Kinetic.Container.drawHit kinetic.js:41
Kinetic.Layer.drawHit kinetic.js:44
Kinetic.Container.drawHit kinetic.js:41
Kinetic.Container.draw kinetic.js:41
tick mainScript.js:221 //This is refering to the myStage.draw() line in my code

更新:

当我用它来删除组件时-

layer.arr[i].remove();

我在同一行收到以下错误

TypeError: Cannot read property '0' of undefined
4

1 回答 1

1

例如,当您创建一个矩形时,您可以像这样删除它:

//create stage have a div with id container:
var stage = new Kinetic.Stage({
                container: 'container',
                width: CANVAS_WIDTH,
                height: CANVAS_HEIGHT
            });

//add layer
var myLayer = new Kinetic.Layer();
stage.add(myLayer);

//add black rectangle to layer
var myRect = new Kinetic.Rect({
x: yourX,
y: yourY,
width: yourWitdh,
height: yourHeight,
fill: 'black'
});
myLayer.add(myRect);

//remove rectangle from layer
myRect.remove();
myLayer.draw()

如果要删除层调用中的所有内容:

myLayer.removeChildren();

您还可以隐藏和显示形状:

rect.show();
rect.hide();

可见属性将设置为真或假。如果为假,则不会绘制。看:

https://github.com/ericdrowell/KineticJS/blob/master/src/Shape.js

if(drawFunc && this.isVisible()) {
                context.save();
                canvas._applyOpacity(this);
                canvas._applyLineJoin(this);                
                canvas._applyAncestorTransforms(this);
                drawFunc.call(this, canvas);
                context.restore();
            }
于 2013-03-30T20:03:31.543 回答