How to use HTML5canvas to draw text: first create the corresponding HTML sample file; then use the fillText method to draw the filled text on the canvas.
If you want to use HTML5 Canvas to draw text, you need to use the fillText() method of the canvas context. Let’s look at the specific content below.
Let’s look at the specific example first
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <meta charset="utf-8"/> <script type="text/javascript"> function draw() { var canvas = document.getElementById('SimpleCanvas'); if ( ! canvas || ! canvas.getContext ) { return false; } var context = canvas.getContext('2d'); context.font = 'normal 18pt "楷体"'; context.fillText('Hello HTML Canvas World!', 60, 200); } </script> </head> <body onload="draw()" style="background-color:#D0D0D0;"> <canvas id="SimpleCanvas" width="640" height="480" style="background-color:#FFFFFF;"></canvas> <div>Canvas Demo</div> </body> </html>
Explanation:
The following code obtains the canvas object and obtains the context .
var canvas = document.getElementById('SimpleCanvas'); if ( ! canvas || ! canvas.getContext ) { return false; } var context = canvas.getContext('2d');
Below is the code for drawing characters. Specifies the font information for the characters to be drawn in the font property. Use the fillText() method to draw a string on the canvas. The string to be drawn as the first argument, the X and Y coordinates of the start of the drawing are given to the second and third arguments.
context.font = 'normal 18pt "楷体"'; context.fillText('Hello HTML Canvas World!', 60, 200);
Running results
Use a web browser to display the above HTML file. Obtain the display result shown below.
Next let’s look at how to change the color of the text
The code is as follows
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <meta charset="utf-8" /> <script type="text/javascript"> function draw() { var canvas = document.getElementById('SimpleCanvas'); if ( ! canvas || ! canvas.getContext ) { return false; } var context = canvas.getContext('2d'); context.font = 'normal 18pt "楷体"'; context.fillStyle = 'red'; context.fillText('你好,PHP中文网!!!', 60, 200); } </script> </head> <body onload="draw()" style="background-color:#D0D0D0;"> <canvas id="SimpleCanvas" width="640" height="360" style="background-color:#FFFFFF;"></canvas> <div>Canvas Demo</div> </body> </html>
Instructions:
Change the text Color, you need to set the fillStyle attribute to the text color.
context.font = 'normal 18pt "楷体"'; context.fillStyle = 'red'; context.fillText('你好,PHP中文网!!!', 60, 200);
Running results:
Use a web browser to display the above HTML file. You will get the effect as shown in the picture below, with red fonts drawn.
The above is the detailed content of How to draw text using HTML5 canvas. For more information, please follow other related articles on the PHP Chinese website!