EN
JavaScript - change text color on canvas
0 points
In this article, we would like to show you how to change text color 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';
5
context.fillStyle = 'red'; // sets text color to red
6
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.
In this example, we use fillStyle()
method to change the color for fillText()
on HTML canvas element to red
.
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
var canvas = document.querySelector('#my-canvas');
15
var context = canvas.getContext('2d');
16
17
context.font = '48px serif';
18
context.fillStyle = 'red'; // sets text color to red
19
context.fillText('Example text', 20, 65);
20
21
</script>
22
</body>
23
</html>