The CanvasRenderingContext2D
.rotate()
method of the Canvas 2D API adds a rotation to the transformation matrix.
void ctx.rotate(angle);
angle
degree * Math.PI / 180
if you want to calculate from a degree value.The rotation center point is always the canvas origin. To change the center point, you will need to move the canvas by using the translate()
method.
This example rotates a rectangle by 45 degrees.
<canvas id="canvas"></canvas>
const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Point of transform origin ctx.arc(0, 0, 5, 0, 2 * Math.PI); ctx.fillStyle = 'blue'; ctx.fill(); // Non-rotated rectangle ctx.fillStyle = 'gray'; ctx.fillRect(100, 0, 80, 20); // Rotated rectangle ctx.rotate(45 * Math.PI / 180); ctx.fillStyle = 'red'; ctx.fillRect(100, 0, 80, 20); // Reset transformation matrix to the identity matrix ctx.setTransform(1, 0, 0, 1, 0, 0);
The center of rotation is blue. The non-rotated rectangle is gray, and the rotated rectangle is red.
Specification | Status | Comment |
---|---|---|
HTML Living Standard The definition of 'CanvasRenderingContext2D.rotate' in that specification. | Living Standard |
Desktop | ||||||
---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
Basic support | Yes | 12 | Yes | Yes | Yes | Yes |
Mobile | |||||||
---|---|---|---|---|---|---|---|
Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
Basic support | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
CanvasRenderingContext2D
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/rotate