在 <canvas> 上将鼠标悬停在图像上进行缩放

2022-01-17 00:00:00 html html5-canvas

我有一个画布,我在上面画了一张图片:

I have a canvas, and I've drawn an image on it:

var imageObj = new Image();
imageObj.onload = function() {
    context.drawImage(imageObj, 0, 0);
};
imageObj.src = 'http://localhost:8080/apache_pb2.png';

但我想在鼠标悬停时缩放图像.所以我尝试了这段代码:

but I want to scale the image on mouse over. So I tried this code:

imageObj.onmouseover = function() {
    context.scale(2, 2);
}

认为我可能会走运 - 但​​不行 - 它甚至没有触发.

thinking I might get lucky -but no go -it doesn't even fire.

但是,雪上加霜的是,我似乎无法在 HTML5 画布上找到明确的参考,因此很难确定 Image 对象上有哪些可用内容.

However, to add insult to injury I can't seem to find a definitive reference on the HTML5 canvas so it's pretty difficult to determine what's available on the Image object.

如何附加到 onmouseover 事件?是否还有 onmouseover 事件?

How can I attach to the onmouseover event? Is there even an onmouseover event?

推荐答案

作为使用库的一个选项,这是一个普通的 Javascript 实现.

As an option to use a library, here is a vanilla Javascript implementation.

基本上我们只需要在画布元素上监听两个事件,mousemovemouseout.我们只是在开始时和 mouseout 上将一半大小的图像绘制到画布上.当鼠标悬停在与鼠标位置相反的位置时,我们会缩放"(全尺寸)绘制图像:

Basically we only need to listen to two events, mousemove and mouseout, both on the canvas element. We just draw the image at half size to the canvas on start and on mouseout. We draw the image "zoomed" (full size) when mouse is over at location negative to mouse position:

如上链接所示-

获取并绘制图像:

var img = document.createElement('img');
img.onload = function() {

    //init geometry
    canvas.width = img.width>>1; //we'll show image at half size
    canvas.height = img.height>>1;

    //drawimage
    doCanvas();

    //add event listener we need
    canvas.addEventListener('mouseout', doCanvas, false);
    canvas.addEventListener('mousemove', move, false);
}

//some image...
img.src ="http://i.imgur.com/pULaM45.jpg";

function doCanvas() {
    ctx.drawImage(img, 0, 0, img.width>>1, img.height>>1);
}

mousemove 上移动:

function move(e) {
    var pos = getMousePos(canvas, e);
    ctx.drawImage(img, -pos.x, -pos.y, img.width, img.height);
}

mouseout 上,我们只是通过调用 doCanvas() 来重置.

On mouseout we just reset by calling doCanvas().

这无需任何复杂的缩放即可工作,因为图像显示为 50%,因此当鼠标位置位于与图像的另一半(四分之一)相对应的右下角时.

This works without any complex scaling as the image is shown at 50% so when mouse position is at the bottom right corner that corresponds with the other half (quarter) of the image.

如果您想说,最初以全尺寸的 25% 显示图像,您需要按比例因子缩放鼠标坐标.

If you want to lets say, show the image initially by 25% of full size, you need to scale the mouse coordinates by a scale-factor.

演示使用了 50% 以外的其他缩放系数.

相关文章