3

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

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

但我想将scale鼠标悬停在图像上。所以我尝试了这段代码:

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

想着我可能会走运——但不行——它甚至没有开火。

然而,雪上加霜,我似乎无法在 HTML5 画布上找到明确的参考,因此很难确定Image对象上有什么可用的。

如何附加到onmouseover事件?甚至有onmouseover活动吗?

4

3 回答 3

6

作为使用库的一个选项,这里有一个 vanilla Javascript 实现

基本上我们只需要在 canvas 元素上监听两个事件,mousemove和。mouseout我们只是在 start 和 on 上将一半大小的图像绘制到画布上mouseout。当鼠标悬停在鼠标位置的负位置时,我们绘制图像“缩放”(全尺寸):

如上面的链接所示 -

获取并绘制图像:

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()

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

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

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

于 2013-06-17T20:38:16.137 回答
3

“缩放”的关键是向用户显示半分辨率的图像。

然后要“放大”,您会弹出一个辅助画布,在较小的“视口”中显示全分辨率图像的一部分。

您可以以此为起点。

它是使用 KineticJS 构建的,但代码在直接的 Canvas/JS 中是相同的。

Kinetic JS 图像放大镜

于 2013-06-17T17:54:22.877 回答
2

Canvas doesn't have a "scene graph". It forgets what you did instantly after you've done it. It's all just pixels, so canvas doesn't know there's any image to hover or scale.

context.scale() doesn't affect any previous operations. It only changes coordinates/sizes for later drawing commands.

You can't attach mouse handlers to things on canvas or modify them after they've been drawn. You have to handle mouse yourself and redraw the canvas yourself.

If you don't do anything much more complex than this, then <canvas> is a bad tool for the task. You may be better off using <img> and CSS :hover or a bit of JS changing style.width.

You could also achieve that with SVG, which does have scene graph and mouse event handlers.

于 2013-06-17T21:47:57.953 回答