EN
JavaScript - draw text on canvas
0 points
In this article, we would like to show you how to draw text on canvas using JavaScript.
Quick solution:
xxxxxxxxxx
1
var canvas = document.querySelector('#canvas-id');
2
var context = canvas.getContext('2d');
3
4
context.font = '48px serif'; // sets font
5
context.fillText('Example text', 20, 65); // draws text
In this example, we present how to create a reusable function that draws text with specified font on canvas element using fillText()
method.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
#my-canvas { border: 1px solid gray; }
7
8
</style>
9
</head>
10
<body>
11
<canvas id="my-canvas" width="300" height="100"></canvas>
12
<script>
13
14
function draw(context, text) {
15
context.font = '48px serif';
16
context.fillText(text, 20, 65); // fillText(text, xStart, yStart);
17
}
18
19
20
// Usage example:
21
22
var canvas = document.querySelector('#my-canvas');
23
var context = canvas.getContext('2d');
24
var text = 'Example text';
25
26
draw(context, text);
27
28
</script>
29
</body>
30
</html>