Search code examples
javascriptkonvajs

custom shape using konvajs not draggable


I am using konvajs to draw a custom shape and the rendering works fine. however, when i try to drag it, it is not draggable.

Please find the link to the code.

Custom shape Not draggable

Please point me in the right direction.

Thankyou.


Solution

  • In Konva.js, it's generally best to avoid using stroke() directly in the sceneFunc. Instead, use the fillStrokeShape function to handle the rendering consistently.

    When drawing custom shapes with multiple curves or lines in Konva.js, it's essential to follow a logical order. For instance, if you want to draw two curves in opposite directions connected by lines, ensure the path starts with the first curve, follows with the connecting line, draws the second curve backward, and finally closes the shape for proper filling.

    var shape = new Konva.Shape({
      sceneFunc: function(context) {
        context.beginPath();
    
        // Draw the first Bezier curve
        context.moveTo(start1.x, start1.y);
        context.bezierCurveTo(control1.x, control1.y, control2.x, control2.y, end1.x, end1.y);
    
        // Draw a line down to the second curve's starting point
        context.lineTo(end2.x, end2.y);
    
        // Draw the second Bezier curve backwards
        context.bezierCurveTo(control4.x, control4.y, control3.x, control3.y, start2.x, start2.y);
    
        // Connect back to the starting point to close the shape
        context.lineTo(start1.x, start1.y);
    
        // Close the path and fill/stroke the shape
        context.closePath();
        context.fillStrokeShape(shape);
      },
      fill: '#00D2FF',
      strokeWidth: 4,
      stroke: 'black',
    });