HTML5 Limit Moving Image Into Canvas

我是研究僧i 提交于 2020-02-25 08:43:11

问题


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 start
    element.translate(x - startX, y - startY);
    drawImage();

    //update start positions for next loop
    startX = x;
    startY = y;
}}

http://jsfiddle.net/braziel/nWyDE/

Friends, I need help to limit the movement of an image within the canvas when zoomed.

I put the link, you can see the image when zoomed and dragged it exceeded the limit of the image.

The image must always stay within the canvas and never move more than that.

Thanks all!


回答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;
}


来源:https://stackoverflow.com/questions/17434359/html5-limit-moving-image-into-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!