在 Kineticjs 中删除数组中的组

Removing Groups within an Array in Kineticjs

本文关键字:数组 删除 Kineticjs      更新时间:2023-09-26

我正在尝试删除包含组(包含形状)或简单形状(线条,矩形,圆形等)作为其元素的数组元素。我的函数如下所示:

deleteSelectedShape = function () {
var i,
    shapeObj,
    selectedObjects = currentContext.getSelectedObjects(),
    shapeLayer = currentContext.getShapeLayer();
   if (selectedObjects && selectedObjects.length > 0) {
    for (i = 0; i < selectedObjects.length; i += 1) {
        shapeObj = selectedObjects[i];
        // shapeObj.remove(); results same error as mentioned at last
             if (shapeObj.nodeType === "Group") {
                    shapeObj.destroyChildren();
             }
              else{
                 shapeObj.destroy();
               }
            }
        }
         selectedObjects = [];
         shapeLayer.draw();
   };

我也试过这个

  if (shapeObj.nodeType === "Group") {
            var childs = [];
            childs = shapeObj.getChildren();
            for (var j = 0; j < childs.length; j++) {
                childs[j].remove();
            }
        }
        else{
             shapeObj.remove();
           }
        }  
    }

在这里,单个形状被删除,但如果数组中有组,则会给出错误:

    TypeError: this.getParent(...) is undefined in Kineticjs file

请建议我正确的想法。谢谢!!!

一个问题:从数组中删除项目时,必须反向遍历该数组。

var i=selectedObjects.length-1;
while( i-- >=0 ){
    var shapeObj = selectedObjects[i];
    if (shapeObj.nodeType === "Group") {
        shapeObj.destroyChildren();
    }else{
        shapeObj.destroy();
    }
}