Canvas How to - Switch two images








Question

We would like to know how to switch two images.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){<!--from  w w w.jav a 2s. c  om-->
    var myImage = new Image();
    myImage.src = "https://www.google.com/images/srpr/logo4w.png";
    var myImage2 = new Image();
    myImage2.src =  "http://www.java2s.com/style/download.png"
    var google = true;
    function runFunction(){
        var can = document.getElementById("canvas").getContext('2d');
        if(google){
            google = false;
            can.fillStyle="#000000";
            can.fillRect(0,0,200,200);
            can.drawImage(myImage2,0,0);
        }
        else{
            google = true;
            can.fillStyle="#000000";
            can.fillRect(0,0,200,200);
            can.drawImage(myImage,0,0);
        }
    }
    var t=setInterval(runFunction,1000);
}//]]>  
</script>
</head>
<body>
  <canvas id="canvas" width="200" height="200">
</canvas>
</body>
</html>

The code above is rendered as follows: