Languages
[Edit]
EN

JavaScript - change text color on canvas

0 points
Created by:
Welsh
902

In this article, we would like to show you how to change text color on canvas using JavaScript.

Quick solution:

var canvas = document.querySelector('#canvas-id');
var context = canvas.getContext('2d');

context.font = '48px serif';
context.fillStyle = 'red'; // sets text color to red
context.fillText('Example text', 20, 65);

Note:

The fillStyle property can be set to a string representing a CSS color value, a gradient or a pattern. By default it is set to black color.

 

Practical example

In this example, we use fillStyle() method to change the color for fillText() on HTML canvas element to red.

// 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>

    var canvas = document.querySelector('#my-canvas');
    var context = canvas.getContext('2d');

    context.font = '48px serif';
    context.fillStyle = 'red'; // sets text color to red
    context.fillText('Example text', 20, 65);

  </script>
</body>
</html>

See also

  1. JavaScript - draw text on canvas

  2. JavaScript - fillStyle vs strokeStyle

References

  1. fillStyle - Web APIs | MDN

Alternative titles

  1. JavaScript - change color for fillText() on HTML5 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