Languages
[Edit]
EN

JavaScript - draw text on canvas

0 points
Created by:
Jan-Alfaro
501

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>

References

  1. Drawing text - Web APIs | MDN
  2. fillText() - Web APIs | MDN

Alternative titles

  1. JavaScript - draw text on HTML canvas element
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - HTML5 canvas tutorial

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join