Canvas How to - Scale image and draw








Question

We would like to know how to scale image and draw.

Answer


<!--from  w  w  w .  j a v a 2 s .c o  m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
    var can = document.getElementById('canvas1');
    var ctx = can.getContext('2d');
    var img = new Image();
    img.onload = function() {
        var s = 5.5;
        ctx.scale(s, s);
        for (var x = 0.3; x < 200; x+=15) {
            for (var y = 0.3; y < 200; y+=15) {
                ctx.drawImage(img, 0, 0, 15+1/s, 15+1/s, x, y, 15+1/s, 15+1/s);
            }
        }
    }
    img.src = "http://www.java2s.com/style/download.png";
}//]]>  
</script>
</head>
<body>
  <canvas id="canvas1" width="400" height="400"></canvas>
</body>
</html>

The code above is rendered as follows: