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:
var canvas = document.querySelector('#canvas-id');
var context = canvas.getContext('2d');
context.font = '48px serif'; // sets font
context.fillText('Example text', 20, 65); // draws text
Practical example
In this example, we present how to create a reusable function that draws text with specified font on canvas element using fillText()
method.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
#my-canvas { border: 1px solid gray; }
</style>
</head>
<body>
<canvas id="my-canvas" width="300" height="100"></canvas>
<script>
function draw(context, text) {
context.font = '48px serif';
context.fillText(text, 20, 65); // fillText(text, xStart, yStart);
}
// Usage example:
var canvas = document.querySelector('#my-canvas');
var context = canvas.getContext('2d');
var text = 'Example text';
draw(context, text);
</script>
</body>
</html>