How to move the canvas like drag and drop?

I need to move the whole canvas by touch like the movement of drag and drop

the position of the canvas is supposed to be from

    flattenCanvas.height = canvas.height = SCREEN_HEIGHT - menu.container.offsetHeight;
canvas.style.position = 'absolute';
canvas.style.top = menu.container.offsetHeight+'px';
 canvas.style.left = -(menu.container.offsetHeight)/2+'px';
context = canvas.getContext("2d");

and the touches for drawing or scrolling is from this

else if(event.touches.length == 1)  ////one finger scrolling
{

       canvas.style.top = (((event.touches[0].pageY)))+'px';
      canvas.style.left = (((event.touches[0].pageX)))+'px';

}

from the last code i can move the canvas by one touch but it is not really dragging. how to fix the canvas screen movement?

this is a demo of the webapp demo

Upvotes: 2

Views: 1586

Answers (1)

A. Vidor
A. Vidor

Reputation: 2550

Based on these docs, the event you want to handle is touchmove.

The code in your question appears to live inside a touchstart handler; just execute the same code in a touchmove handler to continuously update during the 'drag'.

Update

What you are trying to do is offset a target element (in this case, a canvas element) by the difference between a touch event's "current" (touchmove) and "start" (touchstart) positions. To do so, you should capture the positions of both target and touch in a touchstart handler. Then, in your touchmove handler, take the difference in touch positions, and add them to the target's start position. This might look like:

// Get your draggable element from the DOM
var draggable = document.getElementById('draggable');

// Set initial position.
draggable.style.position = 'relative'; // 'absolute' also works.
draggable.style.top = '0';
draggable.style.left = '0';

var targetStartX, targetStartY, touchStartX, touchStartY;

// Capture original coordinates of target and touch
function dragStart(e) { 
  targetStartX = parseInt(e.target.style.left);
  targetStartY = parseInt(e.target.style.top);
  touchStartX  = e.touches[0].pageX;
  touchStartY  = e.touches[0].pageY;
}
function dragMove(e) { 
  // Calculate touch offsets
  var touchOffsetX = e.touches[0].pageX - touchStartX,
      touchOffsetY = e.touches[0].pageY - touchStartY; 
  // Add touch offsets to original target coordinates,
  // then assign them to target element's styles. 
  e.target.style.left = targetStartX + touchOffsetX + 'px'; 
  e.target.style.top  = targetStartY + touchOffsetY + 'px';
}
draggable.addEventListener('touchstart', dragStart);
draggable.addEventListener('touchmove',  dragMove);

Here's a live demo.

Upvotes: 2

Related Questions