JavaScript Answers

How to Draw Rotated Text on an HTML5 Canvas?

Spread the love

To draw rotated text on an HTML5 canvas, we can use the canvas context’s rotate method to rotate the contents.

For instance, we can write the following HTML to create the canvas:

<canvas style='width: 300px; height: 200px'></canvas>

Then we write:

const canvas = document.querySelector("canvas");  
const ctx = canvas.getContext("2d");  
ctx.rotate(Math.PI / 4);  
ctx.font = "30px Arial";  
ctx.fillText("Hello World", 50, 0);

to create the canvas content.

We get the canvas element with document.querySelector .

Then we get the context with canvas.getContext .

Next, we call rotate with the angle to rotate in radians.

Then we set the font to draw the text by assigning a value to the font property.

Finally, we call fillText to draw the text with the given string and x and y coordinates of the top left corner.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *