user1942359
user1942359

Reputation: 1639

an image as a button

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

Answers (3)

MJQ
MJQ

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

rezoner
rezoner

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

karaxuna
karaxuna

Reputation: 26930

Take a look at kineticjs tutorial (what you want is made easier)

Upvotes: 1

Related Questions