toggle image in canvas - Javascript Canvas

Javascript examples for Canvas:image

Description

toggle image in canvas

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>http://stackoverflow.com/questions/10215408/toggle-image-in-canvas</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
      <style id="compiled-css" type="text/css">

#canvas {//from www .  j  av a  2s .com
   background-color:red;
}


      </style> 
      <script type="text/javascript">
    $(window).load(function(){
var myButton = new Image();
var mouseX = 0;
var mouseY = 0;
var backgroundImage = new Image();
var nothing = "http://dummyimage.com/100x100/000/fff&text=nothing";
var something = "http://dummyimage.com/100x100/000/fff&text=somthing";
function drawButton(buttonObj) {
    canvasContext.drawImage(buttonObj, buttonObj.x, buttonObj.y);
}
function checkIfInsideButtonCoordinates(buttonObj, mouseX, mouseY) {
    if (((mouseX > buttonObj.x) && (mouseX < (buttonObj.x + buttonObj.width))) && ((mouseY > buttonObj.y) && (mouseY < (buttonObj.y + buttonObj.height)))) {
        return true;
    }
    else {
        return false;
    }
}
$(function() {
    var canvas = $("#canvas").get(0);
    canvasContext = canvas.getContext('2d');
    backgroundImage.src = "http://dummyimage.com/100x100/000/fff&text=back";
    $(backgroundImage).load(function() {
        canvasContext.drawImage(backgroundImage, 0, 0);
        myButton.x = 100;
        myButton.y = 100;
        myButton.width = 100;
        myButton.height = 100;
        myButton.src = something;
        drawButton(myButton);
    });
    $("#canvas").click(function(eventObject) {
        debugger;
        mouseX = eventObject.pageX - this.offsetLeft;
        mouseY = eventObject.pageY - this.offsetTop;
        if (checkIfInsideButtonCoordinates(myButton, mouseX, mouseY)) {
            if (myButton.src == something) {
                myButton.src = nothing;
            }
            else if (myButton.src == nothing) {
                myButton.src = something;
            }
            drawButton(myButton);
        }
    });
});
    });

      </script> 
   </head> 
   <body> 
      <canvas id="canvas" width="165px" height="145px"></canvas>  
   </body>
</html>

Related Tutorials