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