Reputation: 935
How can I make an image in a canvas to act as a link? I am not able to put < a href > tag on the < image > tag as I dont want it to be displayed first until the user click on a button.
Is there any line of code I need to insert in the javascript?
window.onload = function () {
var endCan = document.getElementById("endCan");
var end = endCan.getContext("2d");
var img = document.getElementById("end");
end.drawImage(img, 0, 0, img.width / 2, img.height / 2);
};
<img id="end" style="display: none;" src="img/WellDone_Rectangle.png"/>
<canvas id="endCan" class="wrapper" width="1000" height="600"></canvas>
$(".buttonNext6").click(function () {
$("#endCan").fadeIn();
});
Upvotes: 2
Views: 78
Reputation: 3103
window.onload = function () {
var endCan = document.getElementById("endCan");
var end = endCan.getContext("2d");
var img = document.getElementById("end");
end.drawImage(img, 0, 0, img.width / 2, img.height / 2);
};
//$(".buttonNext6").click(function () {
// $("#endCan").fadeIn();
//});
function canvasCallback() {
console.log('clicked')
}
<img id="end" style="display: none;" src="https://picsum.photos/200/300"/>
<canvas onclick="canvasCallback()" id="endCan" class="wrapper" width="1000" height="600"></canvas>
Upvotes: 0
Reputation: 26143
You need to add a click event handler to the canvas, and then when it's clicked you check the co-ordinates to see if it was clicked where your image was drawn.
Here's an example, using a rectangle drawn on a canvas...
var endCan = document.getElementById("endCan");
var endCtx = endCan.getContext("2d");
endCtx.rect(10, 20, 150, 100);
endCtx.fill();
endCan.addEventListener("click", function(e) {
if (e.clientX >= 10 && e.clientX <= 160 &&
e.clientY >= 20 && e.clientY <= 120) {
alert("clicked");
}
});
<canvas id="endCan" class="wrapper" width="500" height="300"></canvas>
Upvotes: 2