As an option to use a library, here is a vanilla Javascript implementation.
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 -
Get and draw the image:
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 around:
function move(e) {
var pos = getMousePos(canvas, e);
ctx.drawImage(img, -pos.x, -pos.y, img.width, img.height);
}
On mouseout
we just reset by calling doCanvas()
.
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.
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.
Demo using other zoom factors than 50%.