What is the best way of turning a Canvas element into a link - by this I mean the whole canvas element, not just a part of the image.
I have tried the obvious thing - wrapping the element in an A element - but finding issues in IE9.
Take this markup for example:
<a href="#link">
<canvas width="100" height="100">
//fallback
</canvas>
</a>
Using CSS I have styled the link background colour to change on hover, and am finding in most modern canvas supporting browsers it works as expected - you hover, the background changes colour, you click the link, the link is followed.
However, in IE9 when hovering over the element it doesn't recognise that it's a link - no hover effect, no cursor changing to a pointer, clicking does nowt.
Interestingly, if I add a 1 pixel border to the A element, and hover the mouse precariously over the 1 pixel border, IE9 does recognise the link, and after that you can move the mouse over the canvas and it maintains it's hover state and works as a link.
It's almost as if the canvas is overriding the link, so the browser isn't able to recognise the link, only the canvas element - if that makes sense?
So, really I just want to ascertain:
Thanks
OK, so the answer's I've had below are all correct, but unfortunately weren't working in my implementation either. My markup is quite a lot more complicated than the simplified example above, so I'm guessing that actually there is something else at play that is causing the problem - with native hover events and events attached with JavaScript - nothing was working.
However, I've come up with a hack that solved the problem. I gave my link an RGBA background colour with zero opacity. Once that was there, things work fine. Weird I know, but fixed :)
I'm not 100% on the problems with the canvas element in IE but you can update the onclick handler of the canvas
element, changing the window location to where you want.
document.getElementById("mycanvas").onclick = function(e){
window.location.href = 'http://www.google.com';
};
Example: http://jsfiddle.net/jonathon/HtmVS/
You could handle other events (like the mousein/mouseout) to set the cursor, if you wanted.
You can use javascript's onclick
to handle this, and combine it with CSS to put a cursor: pointer;
on it. You could then implement canvas:hover
in CSS for the hover effects. You can combine this with an <a>
to allow the user to "tab" through the links/canvases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With