Canvas How to - Translate along with image size








Question

We would like to know how to translate along with image size.

Answer


<!--   w  w  w . j  av  a2  s .co m-->

<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
    image.onload = function () {
        var ctx = canvas.getContext('2d');
        ctx.translate(image.width * 0.5, image.height * 0.5);
        ctx.rotate(0.5 * Math.PI);
        ctx.translate(-image.width * 0.5, -image.height * 0.5);
        ctx.drawImage(image, 0, 0);
        var dataUri = canvas.toDataURL();
        console.log(dataUri);
    }
    image.src="http://www.java2s.com/style/download.png";
}//]]>  
</script>
</head>
<body>
  <img id="image"  alt="" />
  <canvas width="557" height="333" id="canvas"></canvas>
</body>
</html>

The code above is rendered as follows: