Canvas How to - Shear image with scale function








Question

We would like to know how to shear image with scale function.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){<!--from ww  w .  j  a v a2  s  . c o  m-->
var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');
ctx.translate(50,50); // just to get away from edge
// show original 200x200 area:
ctx.fillStyle = 'lightblue';
ctx.fillRect(0,0,200,200);
var img = new Image();
img.onload = function() {
    // rotation first
    ctx.translate(100,100);
    ctx.rotate(.3);
    ctx.translate(-100,-100);
    // than scale
    ctx.translate(0,200 * (1/3) / 2) // move by half of the 1/3 space to center it
    ctx.scale(1, 2/3); // squish it to 2/3 vertical size
    ctx.drawImage(img, 0,0);
}
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: