Home > Article > Web Front-end > How to set the font color of HTML5 canvas? (code example)
In the HTML5 canvas, we can use the fillStyle attribute to set the font color of the text. It can accept a color code value, such as #cc0000, or an English word of a color, such as red. Let’s take a look at it below, hoping it will be helpful to everyone. [Video tutorial recommendation: HTML tutorial]
First we need to create a canvas using the canvas tag in the HTML page and set its id value to myCanvas.
<canvas id="myCanvas"></canvas>
Then use JavaScript to draw text graphics in the canvas
1. Get the canvas control
var canvas = document.getElementById("myCanvas");// 查找画布元素
2. Use the getContext() method to configure the drawing environment and create the drawing object
var ctx = canvas.getContext("2d");
3. Use the fillText method to write text in the canvas. The parameters are the text content and the location of the text.
We can also use the font attribute to set the font size and font type of the text.
ctx .font="20px 微软雅黑"; ctx .fillText('PHP中文网',20,20,200);
Rendering:
You can see that the text displayed on the page is the default black text.
3. If you want to set the font color of text, you need to use the fillStyle attribute. This attribute can accept a color code value, such as #cc0000, or an English word of a color, such as red.
ctx .fillStyle="red";
Complete js code:
<canvas id="myCanvas"></canvas>
Rendering:
The above is the entire content of this article, I hope it can be helpful to everyone Learning helps. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !
The above is the detailed content of How to set the font color of HTML5 canvas? (code example). For more information, please follow other related articles on the PHP Chinese website!