Canvas How to - Resize image in drawImage methods








Question

We would like to know how to resize image in drawImage methods.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){<!-- www .  jav  a 2 s  . co m-->
    var example = document.getElementById('example'),
        ctx     = example.getContext('2d'),
        pic     = new Image();
    example.height = 300;
    example.height = 450;
    pic.src = 'http://www.java2s.com/style/download.png';
    pic.onload = function () {
       
        ctx.drawImage(pic, 0, 0);
     
        ctx.drawImage(pic, 0, 130, 300, 150);
     
        ctx.drawImage(pic, 25, 42, 85, 55, 0, 300, 170, 110);
    }
}
</script>
</head>
<body>
  <canvas id='example'</canvas>
</body>
</html>

The code above is rendered as follows: