且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

HTML5将移动图像限制为画布

更新时间:2023-02-24 17:57:38

第一步是跟踪图像的绝对位置。为此我在全球范围内添加了这个:

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

var ix=0, iy=0;

接下来,我们计算 mousemove 事件新头寸和旧头寸之间的差异:

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

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

然后我们需要找到缩放图像和画布之间的差异。由于画布不知道它是缩放的(我们使用的坐标是一如既往的1:1)我们需要与画布的缩放尺寸进行比较。由于我们跟踪当前比例,我们只是乘以那些作为因子,减去图像维度并将所有内容除以2以使其居中:

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;

现在我们可以检查我们的边界 - 如果在外面我们将delta值重置为0,那么没有任何内容被翻译:

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;

最后我们用我们的delta值更新翻译:

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

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

如果外部边界没有任何改变,那么delta将为0,在这种情况下,每个轴都是分开的。如上所述,我们使用坐标,就好像没有任何内容被缩放和旋转,因为画布只是项目我们对翻译矩阵的所有内容。因此,我们无需担心轮换。

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.

此处产生的演示:

改进的小提琴

此外 - 由于我们在移动图像时遇到风险而将鼠标光标移到画布外,因此鼠标向上事件将永远不会在画布中注册。因此我们会听取窗口,所以我们确定(除了在iframe中的小提琴中)我们可以重置移动:

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