Canvas How to - Scale and rotate image








Question

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

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){<!-- w  w  w .j  a va2 s.  c o  m-->
var imgRes=['http://placehold.it/300x300',
           'http://placehold.it/300x300',
           'http://placehold.it/300x300'];
var images=[new Image(),new Image(),new Image()];
for(var i=0;i<3;i++) {
    images[i].src=imgRes[i];
}
var canvas=document.getElementById("test"),
    ctx=canvas.getContext("2d");
// image[0]
ctx.save();
ctx.beginPath();
ctx.rect(5,5,190,190);
ctx.closePath();
ctx.clip();
ctx.drawImage(images[0],0,0);
ctx.restore();
// image[1]
ctx.save();
ctx.beginPath();
ctx.rect(5,205,190,190);
ctx.closePath();
ctx.clip();
ctx.drawImage(images[1],0,0);
ctx.restore();
// image[2]
ctx.save();
ctx.beginPath();
ctx.rect(205,5,190,390);
ctx.closePath();
ctx.clip();
ctx.drawImage(images[2],0,0);
ctx.restore();
// image[2]+++
ctx.save();
ctx.translate(200,200);
ctx.rotate(35*Math.PI/180);
ctx.beginPath();
ctx.rect(-80,-80,160,160);
ctx.closePath();
ctx.clip();
ctx.drawImage(images[2],-100,-100,200,200);
ctx.strokeStyle="#00ff80";
ctx.lineWidth=3;
ctx.stroke();
ctx.restore();
}//]]>  
</script>
</head>
<body>
  <canvas id='test' width='400px' height='400px'
    style='background-color: orange;'></canvas>
</body>
</html>

The code above is rendered as follows: