作为使用库的一个选项,这里有一个 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% 以外的其他缩放系数。