Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making an image scale on mouse over on a <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.

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.

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

like image 979
Mike Perrenoud Avatar asked Sep 01 '25 16:09

Mike Perrenoud


2 Answers

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%.

The key to "zooming" is to show the user an image at half resolution.

Then to "magnify" you pop-up a secondary canvas showing a portion of the full resolution image in a smaller "viewport".

You might use this as a starting point.

It's built using KineticJS but the code would be the same in straight Canvas/JS.

Kinetic JS image Magnifier

like image 23
markE Avatar answered Sep 04 '25 07:09

markE