Reputation: 1639
I want an image that I added into a canvas to work as a button. When I clicked the image, an alert must shown. Also clicking the rest of the canvas must be forbidden. How can I do this? Thanks.
<script>
window.onload = function(){
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var quizbg = new Image();
quizbg.src = "basla.png";
context.drawImage(quizbg,0,0);
}
<script>
<body>
<div id="ccontainer">
<canvas id="myCanvas" width="600" height="400"></canvas>
</div>
</body>
Upvotes: 0
Views: 97
Reputation: 1786
Do like this,
<script>
window.onload = function(){
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var quizbg = new Image();
quizbg.src = "basla.png";
quizbg.onload = function() {
context.drawImage(quizbg,0,0);
}
canvas.onclick= function() {
alert('Bike');
canvas.onclick = false;
}
}
</script>
<body>
<div id="ccontainer">
<canvas id="myCanvas" width="600" height="400"></canvas>
</div>
</body>
Working example, http://jsfiddle.net/wcxc2/
Upvotes: 1
Reputation: 1967
You have to write all the logic by yourself.
1) use
canvas.addEventListener("click", function(e) {
e.pageX, e.pageY;
});
to bind mouse
2) check if the click is within the rectangle of a button
if(inRect(e.pageX, e.pageY, buttonX, buttonY, buttonWidth, buttonHeight)) {
alert("the button has been clicked");
}
Of course you have to write inRect function :)
The other thing is that if your canvas is not at [0, 0] you will have to substract its offset from the event's position.
Here is the logic with use of canvasquery http://cssdeck.com/labs/svleh8dq
Upvotes: 0