Canvas How to - Draw image when it is ready








Question

We would like to know how to draw image when it is ready.

Answer


<!--   w w w .jav  a2 s  .c  o  m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
    var canvas = document.getElementById("idd");
    var ctx = canvas.getContext("2d");
    var imageReady = false;
    img = new Image(); 
    img.onload = loaded;
    img.src = 'http://www.java2s.com/style/download.png';
    function loaded() { 
       imageReady = true;
       redraw(); 
    }
    function redraw() {
        if (imageReady) {
            ctx.fillStyle = "white";
            ctx.fillRect(10,10,10,10);
            ctx.drawImage(img, 5, 5);
        }
    }
}//]]>  
</script>
</head>
<body>
  <canvas id="idd"></canvas>
</body>
</html>

The code above is rendered as follows: