Search code examples
javascriptkineticjs

Make drag and drop canvas object using kineticjs


I have multiple canvas object in the toolbar. i want add drag and drop feature to canvas object like fiddle. How can i do this?

JS Code

  $(function(){   
   var stage = new Kinetic.Stage({
        container: 'toolbar',
        width: 350px,
        height: 350px
   });
  var layer = new Kinetic.Layer();
  stage.add(layer);
  var line = new Kinetic.Shape({
      x:0,
      y:0,
      stroke:"blue",
      fill: 'black',
      drawFunc: function(context) {
        context.beginPath();
        context.moveTo(20,5);
        context.quadraticCurveTo(10, 35, 20, 60);
        context.moveTo(20,5);
        context.quadraticCurveTo(30, 35, 20, 60);
        context.fillStrokeShape(this);
      }
    });
    var line2 = new Kinetic.Rect({
        x: 60,
        y: 8,
        width: 40,
        height: 40,
        fill: "red",        
    });     
    layer.add(line);
    layer.add(line2);
    layer.draw();
 });

Solution

  • Canvas content cannot be dragged off the canvas element.

    So if your top toolbar is a canvas containing canvas shapes, then those shapes cannot be dragged off the toolbar onto the second canvas below.

    Several workarounds:

    1. Instead of using a toolbar div and a canvas dropzone, make 1 canvas that draws both your toolbar and your drop zone. That way you can drag your content from the top of the canvas (where the toolbar is) to the bottom part of the canvas (where the dropzone is).

    2. Turn each of your shapes into images. You can do this by:

      • Drawing 1 shape onto a canvas element.
      • Get the dataURL of the canvas using context.getDataURL.
      • Create a new Image() object using the dataURL as the source.
      • Put that newly created shape-image into your toolbar.
      • Repeat for each of your other shapes.

    Good luck with your project!