【问题标题】:konva js make an object not draggablekonva js使对象不可拖动
【发布时间】:2020-10-21 03:24:20
【问题描述】:

我需要创建一个函数,将对象(圆)的属性从可拖动更改为不可拖动。 使用鼠标操作也是理想的,但鼠标用于拖动对象,因此可能需要用鼠标单击它以使其处于活动状态,然后按一个按钮来更改属性。

这是我用来创建圆的代码,新函数需要更改属性draggable。

function addCircle(){
        var circle = new Konva.Circle({
          x: stage.width() / 2,
          y: stage.height() / 2,
          radius: 70,
          fill: 'red',
          stroke: 'black',
          strokeWidth: 4,
          draggable: true,
          id: [ident],
          name: 'test',
        });
      // add the shape to the layer
      layer.add(circle);

      // add the layer to the stage
      stage.add(layer);
    };

提前感谢您的帮助。

【问题讨论】:

  • 欢迎沃尔特。 shape 属性 draggable(bool) 控制形状是否可拖动。要关闭拖动,请使用 shape.draggable(false),或者在之前禁用拖动时使用 true 启用拖动。

标签: function html5-canvas konvajs


【解决方案1】:

如果您想使用鼠标操作来切换draggable 值,您可以这样做:

circle.on('click tap', () => {
  circle.draggable(!circle.draggable());
});

【讨论】:

    【解决方案2】:

    Lavrton,感谢您的意见... 我已尝试添加您推荐的代码,但出现以下错误

    (index):35 Uncaught ReferenceError: circle is not defined.

    我的圈子函数在“konva_library.js”中,所以我认为问题在于事件正在寻找尚未定义的圈子。

    <!DOCTYPE html>
    <html>
        <head>
    
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <title>Konvajs</title>
            <script src='konva_library.js'></script>
            <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/konva/7.0.0/konva.min.js"></script>
    
            </head>
    
        <body>
    
            <div>
                <button onclick="addCircle()">Add Circle</button>
                    <div id='container'></div>
            </div>
    
            <script>
    
                var width = window.innerWidth;
                var height = window.innerHeight;
                var stage = new Konva.Stage({
                    container: 'container',
                    width: width,
                    height: height
                });
    
                var layer = new Konva.Layer();
                stage.add(layer);
    
                // (index):35 Uncaught ReferenceError: circle is not defined
    
                circle.on('dblclick', () => {
                    circle.draggable(!circle.draggable());
                });
    
            </script>
    
        </body>
    
    </html>
    

    【讨论】:

    • 你说得对,因为你的圈子是在点击添加圈子按钮时添加的,所以这个圈子点击事件不能绑定到尚未存在的圈子上!这是一个通用的 JS 问题,与 Konva 无关。在未来对象上设置侦听器称为“委托”,并且您将侦听器设置在父对象上。 Konva 在教程中有一个演示,但它使用单一形状,所以我做了一个修改版本here。请注意,这会在侦听器之前创建形状,但它仍然是委托的演示。
    猜你喜欢
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-28
    • 1970-01-01
    相关资源
    最近更新 更多