Explain Codes LogoExplain Codes Logo

How can I write text on a HTML5 canvas element?

html
responsive-design
canvas
text-alignment
Alex KataevbyAlex Kataev·Dec 6, 2024
TLDR

Create canvas text by calling fillText() on the CanvasRenderingContext2D object. Set font to define text size and style, and fillStyle for text color. Here's a snippet to get you started:

let canvas = document.getElementById('myCanvas'); let ctx = canvas.getContext('2d'); ctx.font = '20px Arial'; // add "px" or else it's not going to work, and you'll feel like a font ctx.fillStyle = 'black'; // because who doesn't like a little black text? ctx.fillText('Hello, Canvas!', 10, 50); // Hello, World is too mainstream

Change up the coordinates (10, 50) to fit the text onto the canvas wherever you like.

Finesse with text alignment

You want your text to sit pretty in horizontal and vertical alignment? Say no more. It's all about playing with textAlign and textBaseline:

ctx.textAlign = 'center'; // align it well, nobody likes off-center stuff ctx.textBaseline = 'middle'; // goes in the middle because it can't decide ctx.fillText('Center of Attention', canvas.width / 2, canvas.height / 2); // Catchy, isn't it?

You can also go all Picasso and rotate or scale your text giving your canvas some dynamism. Unleash your creativity!

ctx.rotate(0.2); // text decided to take a little tilt ctx.fillText('Just Hanging About', canvas.width / 2, canvas.height / 2);

Add a stroke to the text

If outlining your text for emphasis or style is your thing, then strokeText() with strokeStyle is your magic wand:

ctx.strokeStyle = 'blue'; // blue because we like to stand out ctx.strokeText('Look, I have an outline!', 10, 100); // Seeks validation, gets an outline

Best practices and understanding canvas measurements

  • Picasso was right about the importance of setting canvas size. It ensures that your text doesn't get distorted due to scaling issues.
  • Customize before you paint. Set fillStyle or font before you draw each piece of text that needs its own unique style.
  • Don't fret if you don't have a tape measure! Use ctx.measureText('Your Text').width to get the width of your text in pixels - incredibly useful for element positioning. It's all in the details.

Dynamic canvas text

Keep you canvas live and kicking by having its content update with certain events. A handy example would be a running clock:

function updateCanvas() { let now = new Date().toLocaleTimeString(); ctx.clearRect(0, 0, canvas.width, canvas.height); // Out with the old, in with the now ctx.fillText(now, 10, 50); // No Rolex needed requestAnimationFrame(updateCanvas); // I request you to loop it, dear function } updateCanvas(); // Loop, there it is!

Achieving HD text printing

For crystal clear text, you've got to cater for device pixel ratio. Here's an upgrade to your toolbox:

let dpr = window.devicePixelRatio || 1; // Because we care about retina support let rect = canvas.getBoundingClientRect(); canvas.width = rect.width * dpr; canvas.height = rect.height * dpr; ctx.scale(dpr, dpr); // This isn't a weight loss program! It's for pixel perfect scaling. ctx.font = '20px Arial'; ctx.fillText('Sharper than a knife', 10, 50);

That slick responsive look

Ensure your canvas text moves and grooves along with the window size, because responsiveness matters:

window.addEventListener('resize', function() { ctx.font = '20px Arial'; ctx.fillText('Flexible as a gymnast!', canvas.width / 2, canvas.height / 2); });

Despite window size changes, your text will always find its center. Just like a Zen master!