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?
As an option to use a library, here is a vanilla Javascript implementation.
Basically we only need to listen to two events,
mousemove
andmouseout
, both on the canvas element. We just draw the image at half size to the canvas on start and onmouseout
. 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:
On
mousemove
move around:On
mouseout
we just reset by callingdoCanvas()
.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
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 changingstyle.width
.You could also achieve that with SVG, which does have scene graph and mouse event handlers.