Canvas How to - Scale an image








Question

We would like to know how to scale an image.

Answer


<!--from  www .  ja  va2s.com-->




<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
 var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
      var x = 10;
      var y = 10;
      var width = 200;
      var height = 137;
      var imageObj = new Image();
      imageObj.onload = function() {
        context.translate(width, 0);
        context.scale(-1, 1);
        context.drawImage(imageObj, x, y, width, height);
       };
      imageObj.src = 'http://www.java2s.com/style/download.png';
}//]]>  
</script>
</head>
<body>
   <canvas id="myCanvas" width="578" height="200"></canvas>
</body>
</html>

The code above is rendered as follows: