通过id删除和拖动相同形状的多个对象

时间:2014-07-29 18:24:59

标签: kineticjs

当连续绘制两个相同形状的对象时,只能找到带有id或name的最新绘制对象。 例如。我连续绘制了两个圆圈,我想单击一个按钮就可以单独删除它们。 场景:选择一个cirlce,单击删除按钮,应删除选中的圆圈。 当前结果:选择cirlcle并单击删除按钮后,仅删除最后绘制的圆圈。然后选择另一个圆圈后,点击删除,圆圈不会被删除。

同样,对于拖动两个相同形状的对象,只会拖动最后一个drwan对象。

1 个答案:

答案 0 :(得分:0)

以下示例说明如何跟踪当前所选(可拖动)的形状,并在按下按钮时将其删除:

<!DOCTYPE html>
<html>
    <head lang="en">
        <meta charset="UTF-8">
        <title>Shape Select and Delete Test</title>
    </head>
    <body>
        <div id="container"></div>
        <script src="http://cdnjs.cloudflare.com/ajax/libs/kineticjs/5.0.6/kinetic.min.js"></script>
        <script>
            var activeShape,
                size = window.innerWidth > window.innerHeight ? window.innerHeight / 3 : window.innerWidth / 3,
                strokeWidth = size / 8,
                layer = new Kinetic.Layer,
                stage = new Kinetic.Stage({
                    width: window.innerWidth,
                    height: window.innerHeight,
                    container: 'container'
                }),
                circle = new Kinetic.Circle({
                    x: strokeWidth + ( size / 2 ),
                    y: strokeWidth + ( size / 2 ),
                    width: size,
                    height: size,
                    fill: 'red',
                    strokeWidth: strokeWidth,
                    draggable: true
                }),
                rect = new Kinetic.Rect({
                    x: strokeWidth,
                    y: strokeWidth + circle.y() + circle.radius(),
                    width: size,
                    height: size,
                    fill: 'red',
                    strokeWidth: strokeWidth,
                    draggable: true
                }),
                text = new Kinetic.Text({
                    x: rect.width() * 1.3,
                    y: rect.height(),
                    text: 'Delete',
                    fill: 'red',
                    fontSize: size / 2,
                    stroke: 'black',
                    strokeWidth: size / 64
                });

            layer.add( circle );
            layer.add( rect );
            layer.add( text );

            stage.add( layer );

            focusShape( circle );
            focusShape( rect );

            layer.draw();

            text.on( 'click', function() {
                if ( activeShape ){
                    activeShape.destroy();
                    activeShape = null;

                    layer.draw();
                }
            });

            function focusShape( shape ){
                shape.on( 'mousedown', function() {
                    if ( activeShape )
                        activeShape.stroke( null );

                    this.stroke( 'black' );

                    activeShape = this;

                    layer.draw();
                })
            }
        </script>
    </body>
</html>

Example