未捕获的TypeError:无法调用方法' getLayer'未定义的

时间:2013-03-30 18:38:34

标签: javascript kineticjs

我正在使用KineticJS,但是当我尝试在舞台上的一个图层上删除两个组件(一个Kinetic.Image实例和一个Kinetic.Text实例)时,我得到了未被捕获的typerror,即使我已将我的代码放入试试阻止。

导致错误的原因是什么?

这是相关代码

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

1 个答案:

答案 0 :(得分: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();

visisble属性将设置为true或false。如果它是假的,则不会被绘制。参见:

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();
            }