The next type of transformation available with the HTML5 canvas API, and quite arguably the handiest, is the rotation transform. In this recipe, we'll first position the canvas context with a translation transform, and then we'll rotate the context with rotate()
method.
Follow these steps to draw a rotated rectangle:
Define the canvas context and the dimensions for the rectangle:
window.onload = function(){ var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); var rectWidth = 150; var rectHeight = 75;
Translate the canvas context and then rotate it by 45 degrees:
// translate context to center of canvas context.translate(canvas.width / 2, canvas.height / 2); // rotate context 45 degrees clockwise context.rotate(Math.PI / 4);
Draw the rectangle:
context.fillStyle = "blue"; context.fillRect(-rectWidth / 2, -rectHeight / 2, rectWidth, rectHeight); };
Embed the canvas tag inside...