Canvas How to - Translate and rotate








Question

We would like to know how to translate and rotate.

Answer


<!DOCTYPE html>
<html>
<head>
<body>
<canvas id="myCanvas" style="width: 600px; height: 400px; border: 1px solid #c3c3c3;"></canvas>
<script type="text/javascript">
window.onload = function(){<!-- w w  w .  j  a  v  a  2s .c  o m-->
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");
    var rectWidth = 150;
    var rectHeight = 75;
    // translate context to center of canvas
    context.translate(20, 40);
    // rotate 45 degrees clockwise
    context.rotate(Math.PI*1.5);
    context.fillStyle = "blue";
    context.font = '14px Verdana';
    context.fillText("test", 0, 0);

};
</script>
</body>
</html>

The code above is rendered as follows: