HTML5 Canvas Tutorial: transform – rotation

Canvas Transformatiion: rotatie

For rotations on the HTML5 Canvas, we can use the rotate() method. The rotation is described by means of an angle in radians:

context.rotate(angle); //angle in radians

Example 1: Canvas Transformations: rotation 45 degrees clockwise. See image 1.

<!doctype html>
<html>
<head>
<title>Canvas Transformaties: rotatie 45 graden met de klok mee </title>
<script> 
function rotation(){

  var canvas = document.getElementById("transformations");
  var context = canvas.getContext("2d");

  var rectangularWidth = 100;
  var rectangularHeight = 100;

  //  Translate context to the center of the Canvas
  context.translate(canvas.width / 2, canvas.height / 2);

  // rotate 45 degrees clockwise
  // Math.PI radians corresponds to 180 degrees
  // Math.PI / 4 corresponds to 45 degrees
  context.rotate(Math.PI / 4);
  context.fillStyle = "red";
  context.fillRect(-rectangularWidth / 2, -rectangularHeight / 2, rectangularWidth, rectangularHeight);

  };

  window.addEventListener("load", rotation, true);
</script>
</head>
<body>	
	<canvas id="transformations" style="border: 1px solid;" width="400" height="210"></canvas>
</body>
</html>
Canvas Transformaties: de translatie.
Image 1. Canvas Transformations: rotation 45 degrees clockwise.

Check this example in your browser

Next tutorial

Leave a comment