Text in HTML Canvas
- Previous Page Canvas Gradients
- Next Page Canvas Images
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:
JavaScript:
const canvas = document.getElementById("myCanvas"); const ctx = canvas.getContext("2d"); ctx.font = "30px Arial"; ctx.fillText("Hello World", 10, 50);
Using strokeText()
Example
Set the font to "30px Arial" and write text on the canvas (without filling):
JavaScript:
const canvas = document.getElementById("myCanvas"); const ctx = canvas.getContext("2d"); ctx.font = "30px Arial"; ctx.strokeText("Hello World", 10, 50);
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:
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);
See Also:
- Previous Page Canvas Gradients
- Next Page Canvas Images