Next page | Contents page |

Dragging a shape

Add extra properties, isTarget and draggable, to each shape in the array, with value true or false (keywords in Javascript). Then we can test whether a "mousedown" event hits a target and whether the target shape is draggable. If both conditions are true then add another two DATA properties to identify the shape that was hit and record the offset vector between the mouse point and the starting point for drawing the shape:


	function handleDown(e)
	{
	  let mpt = getMousePoint(e);
	  for (let i = 0; i < DATA.shapes.length; i++)
	  {
	    let si = DATA.shapes[i];
	    if (si.isTarget && si.draggable)
	    {
	      switch (si.kind)
	      {
	        case "rect":
	          //if mpt inside si - see the targets page
	          {
	            DATA.hitShape = si;
	            DATA.offset = {dx:mpt.x - si.x, dy:mpt.y - si.y};
	          }
	          break;
	        case "path":
	          //if mpt inside si - see the targets page
	          {
	            DATA.hitShape = si;
	            let p0 = si.path[0];
	            DATA.offset = {dx:mpt.x - p0.x, dy:mpt.y - p0.y};
	          }
	          break;
	        // other cases...
	      }
	    }
	  }
	}

Then the "mousemove" listener will be able to reposition that particular shape and redraw everything.

Next page | Contents page |