Skip to content Skip to sidebar Skip to footer

Html5 Limit Moving Image Into Canvas

canvas.onmousemove = function (e) { if (isDown === true) { var pos = getMousePos(canvas, e); var x = pos.x; var y = pos.y; //translate difference from now and star

Solution 1:

First step is to keep track of image's absolute position. For this I added this in the global:

var ix=0, iy=0;

Next, on the mousemove event we calculate the difference between the new position and the old:

var dx = x - startX;
var dy = y - startY;

And then we need to find with the diffence between the zoomed image and the canvas. As the canvas does not know it is zoomed (sort of - the coordinates we are using are in 1:1 as always) we need to compare to the scaled size of the canvas. Since we keep track of current scale we just multiply with those as a factor, subtract the image dimension and divide everything on 2 to center it:

var diffX = (canvas.width * currentScale - image.width) / 2;
var diffY = (canvas.height * currentScale - image.height) / 2;

Now we can check our boundaries - if outside we reset the delta values to 0 so nothing is translated:

if (ix + dx < -diffX ||
    ix + dx + image.width > canvas.width * currentScale - diffX) dx = 0;

if (iy + dy < -diffY ||
    iy + dy + image.height > canvas.height * currentScale - diffY) dy = 0;

And finally we update the translate with the delta values we have:

ix += dx; //image position
iy += dy;
element.translate(dx, dy);

As delta would be 0 if outside boundaries nothing is changed in that case separate for each axis. As mentioned above, we use the coordinates as if nothing is scaled and rotated as the canvas only project what we have to the translation matrix. Therefor we don't need to worry about rotation.

Resulting demo here:

Modified fiddle

Additionally - as we run into the risk while moving the image around to have the mouse cursor outside canvas, the mouse up event will never register with the canvas. Therefor we listen to the window instead so we are sure (except from when in in an iframe as on fiddle) that we can reset the moving:

window.onmouseup = function (e) {
    isDown = false;
}

Post a Comment for "Html5 Limit Moving Image Into Canvas"