Categories
HTML JavaScript Web development

HTML Canvas Text

HTML Canvas Text

To start to draw text on a canvas, use the following properties and methods:

font

fillText(text,x,y)

strokeText(text,x,y)

The HTML canvas font property sets the current font properties for text content on the canvas. The HTML canvas fillText() method draws filled text on the canvas, and the HTML canvas strokeText() method draws text (no fill) on the canvas.

Example1: Filled Text

<!DOCTYPE html>
<html>
<body>

<canvas id="basicText" width="200" height="100"
style="border:1px solid #333;">
</canvas>

<script>
var canvas = document.getElementById("basicText");
var ctx = canvas.getContext("2d");
ctx.font = "25px Verdana";
ctx.fillText("Hello World",27,60);
</script>

</body>
</html>

Output:

Example2: Stroke Text

<!DOCTYPE html>
<html>
<body>

<canvas id="basicText" width="200" height="100"
style="border:1px solid #333;">
</canvas>

<script>
var canvas = document.getElementById("basicText");
var ctx = canvas.getContext("2d");
ctx.font = "25px Verdana";
ctx.strokeText("Hello World",27,60);
</script>

</body>
</html>

Output:

HTML canvas stroke text

To fill text in color add fillStyle property, and to align the text add the textAlign property.

The HTML canvas textAlign property sets the current alignment for text content, according to the anchor point.
The HTML canvas textAlign can have the following values:
center/ end/ left/ right/ start(default).

Example:

<!DOCTYPE html>
<html>
<body>

<canvas id="alignCanvas" width="300" height="200"
style="border:1px solid #333;">
</canvas>

<script>
var canvas = document.getElementById("alignCanvas");
var ctx=canvas.getContext("2d");
ctx.font="30px Tahoma";
ctx.fillStyle = "#e76f51";
ctx.textAlign = "center";
ctx.fillText("Hello World", canvas.width/2, canvas.height/2);
</script>

</body>
</html>

Output:


The HTML canvas measureText() method returns an object that contains the width of the specified text (you can use this method if you need to know the width of a text, before writing it on the canvas.).

Example:

<!DOCTYPE html>
<html>
<body>

<canvas id="measureText" width="300" height="150" style="border:1px solid #333;"></canvas>

<script>
var c = document.getElementById("measureText");
var ctx = c.getContext("2d");
ctx.font = "25px Tahoma";
var txt = "Hello World"
ctx.fillText("width:" + ctx.measureText(txt).width, 10, 50);
ctx.fillText(txt, 10, 100);
</script>

</body>
</html>

Output:


Enjoy coding!