3
votes

I am just going through a HTML5 Canvas tutorial. http://www.html5canvastutorials.com/kineticjs/html5-canvas-drag-and-drop-events-tutorial/

I want to drag an object in a specific area in the canvas and that object should not drag out from that area. How can I achieve this ?

1

1 Answers

1
votes

http://www.html5canvastutorials.com/kineticjs/html5-canvas-drag-and-drop-bounds-tutorial-with-kineticjs/

You have to define a custom drag-bounds function to limit where the object can be dragged. Like so:

    var yellowGroup = new Kinetic.Group({
      x: stage.getWidth() / 2,
      y: 70,
      draggable: true,
      dragBoundFunc: function(pos) {   // <--- starting here
        var x = stage.getWidth() / 2;
        var y = 70;
        var radius = 50;
        var scale = radius / Math.sqrt(Math.pow(pos.x - x, 2) + Math.pow(pos.y - y, 2));
        if(scale < 1)
          return {
            y: Math.round((pos.y - y) * scale + y),  //<--- you have to return an object like {x: number, y: number }
            x: Math.round((pos.x - x) * scale + x)
          };
        else
          return pos;
      } // this bounds the dragging into a circle area.
    });

Essentially, its just a bit of math which determines where you can set a point.