在< canvas>上鼠标悬停时缩放图像 [英] Making an image scale on mouse over on a <canvas>

查看:201
本文介绍了在< 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';

但我希望 scale 图片上鼠标移到。所以我尝试了这段代码:

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画布上找到明确的参考,因此很难确定<$ c上的可用内容$ c>图像对象。

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.

基本上我们只需要听两个事件, mousemove mouseout ,两者都在canvas元素上。我们只是在开始时和#code> 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:

如上面的链接所示 -

As shown on the link above -

获取并绘制图像:

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

On mousemove move周围:

On mousemove move around:

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%

Demo using other zoom factors than 50%.

这篇关于在&lt; canvas&gt;上鼠标悬停时缩放图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆