Text in HTML Canvas

Drawing text on the canvas

The most important property and method to draw text on the canvas are:

  • font - Defines the font property of the text
  • fillText(text,x,y) - Draw "filled" text on the canvas
  • strokeText(text,x,y) - Draw text on the canvas (without filling)

Using fillText()

Example

Set the font to "30px Arial" and write filled text on the canvas:

Your browser does not support the HTML5 canvas tag.

JavaScript:

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World", 10, 50);

Try It Yourself

Using strokeText()

Example

Set the font to "30px Arial" and write text on the canvas (without filling):

Your browser does not support the HTML5 canvas tag.

JavaScript:

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.strokeText("Hello World", 10, 50);

Try It Yourself

Add color and center the text

Example

Set the font to "30px Comic Sans MS" and write filled red text in the center of the canvas:

Your browser does not support the HTML5 canvas tag.

JavaScript:

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.font = "30px Comic Sans MS";
ctx.fillStyle = "red";
ctx.textAlign = "center";
ctx.fillText("Hello World", canvas.width/2, canvas.height/2);

Try It Yourself

See Also:

Complete Canvas Reference Manual of CodeW3C.com