HTML5 panning based on mouse movement

I am trying to implement the functionality for "panning" inside a canvas in HTML5, and I'm not sure how best to do this.

Currently - I am trying to determine where the mouse is on the canvas, and if it is within 10% of the edge, it will move in this direction, as shown below:

Current Edge Detection:

canvas.onmousemove = function(e) { var x = e.offsetX; var y = e.offsetY; var cx = canvas.width; var cy = canvas.height; if(x <= 0.1*cx && y <= 0.1*cy) { alert("Upper Left"); //Move "viewport" to up and left (if possible) } //Additional Checks for location } 

I know that perhaps I could do this by creating paths in the canvas and associating events with them, but I did not work with them much, so I thought I would ask here. Also - if the "enveloping" panorama was possible, which would be amazing (panning to the left will be directed over time).

Summary: I wonder what the best route to achieve panning is within the HTML5 Canvas. It will not use images, but really drawn objects (if that matters). I will be happy to answer any questions if I can.

Demo:

Demo

+4
source share
2 answers

It depends on how you want panning with mouse movement to be implemented, but today it often uses "real-time panning" to let you move around. I tried updating your fiddle a bit: http://jsfiddle.net/pimvdb/VWn6t/3/ .

 var isDown = false; // whether mouse is pressed var startCoords = []; // 'grab' coordinates when pressing mouse var last = [0, 0]; // previous coordinates of mouse release canvas.onmousedown = function(e) { isDown = true; startCoords = [ e.offsetX - last[0], // set start coordinates e.offsetY - last[1] ]; }; canvas.onmouseup = function(e) { isDown = false; last = [ e.offsetX - startCoords[0], // set last coordinates e.offsetY - startCoords[1] ]; }; canvas.onmousemove = function(e) { if(!isDown) return; // don't pan if mouse is not pressed var x = e.offsetX; var y = e.offsetY; // set the canvas' transformation matrix by setting the amount of movement: // 1 0 dx // 0 1 dy // 0 0 1 ctx.setTransform(1, 0, 0, 1, x - startCoords[0], y - startCoords[1]); render(); // render to show changes } 
+10
source

The pimvdb violin demonstrates the concept beautifully, but it actually does not work, at least not for me.

Here's the fixed version: http://jsfiddle.net/VWn6t/173/
Its meat is basically the same.

 var startCoords = {x: 0, y: 0}; var last = {x: 0, y: 0}; var isDown = false; canvas.onmousemove = function (e) { if(isDown) { ctx.setTransform(1, 0, 0, 1, xVal - startCoords.x, yVal - startCoords.y); } }; canvas.onmousedown = function (e) { isDown = true; startCoords = {x: e.pageX - this.offsetLeft - last.x, y: e.pageY - this.offsetTop - last.y}; }; canvas.onmouseup = function (e) { isDown = false; last = {x: e.pageX - this.offsetLeft - startCoords.x, y: e.pageY - this.offsetTop - startCoords.y}; }; 
+8
source

All Articles