In HTML5, we can also draw the text we need on the Canvas "canvas". CanvasRenderingContext2D
The main properties and methods of the objects involved are as follows:
font | Sets the font used to draw text, for example 20px 宋体 , the default is 10px sans-serif . The usage of this property is consistent with the css font property, for exampleitalic bold 14px/30px Arial,宋体 |
fillStyle | Used to set the color, gradient, and pattern inside the brush fill path. The value of this property can be a string representing a CSS color value. If your drawing needs are more complex, the value of this property can also be an CanvasGradient object or an CanvasPattern object |
strokeStyle | Used to set the color, gradient, and mode of the brush's drawing path. The value of this property can be a string representing a CSS color value. If your drawing needs are more complex, the value of this property can also be an CanvasGradient object or an CanvasPattern object |
fillText(string text, int x, int y[, int maxWidth]) | Draws filled text text starting from the specified coordinate point. The parameter maxWidth is optional, if the text content width exceeds the parameter setting, the font will be automatically scaled down to fit the width. The style setting property corresponding to this method is fillStyle . |
strokeText(string text, int x, int y[, int maxWidth]) | Draws a non-filled text text (the text is hollow inside) starting from the specified coordinate point. The parameter maxWidth is optional, if the text content width exceeds the parameter setting, the font will be automatically scaled down to fit the width. This method is the same as the fillText() usage, but strokeText() the drawn text is non-filled (hollow) inside, and the fillText() drawn text is filled (solid) inside. The style setting property corresponding to this method is strokeStyle . |
From the above API description information, we can know that there are two ways to draw text in Canvas: one is to use fillText()+fillStyle
to draw filled (solid) text; the other is to use to strokeText()+strokeStyle
draw non-filled (hollow) text .
Next, let's take a look at how to use canvas to draw solid text. The specific html code is as follows:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>HTML5 Canvas drawing text text entry example</title> </head> <body> <!-- Add canvas tag with red border for easy viewing on the page--> <canvas id="myCanvas" width="400px" height="300px" style="border: 1px solid red;"> Your browser does not support the canvas tag. </canvas> <script type="text/javascript"> //Get the Canvas object (canvas) var canvas = document.getElementById("myCanvas"); //Simply detect whether the current browser supports Canvas objects, so as to avoid syntax errors in some browsers that do not support html5 if(canvas.getContext){ //Get the corresponding CanvasRenderingContext2D object (brush) var ctx = canvas.getContext("2d"); //set font style ctx.font = "30px Courier New"; //set font fill color ctx.fillStyle = "blue"; //Start drawing text from coordinate point (50,50) ctx.fillText("CodePlayer+Chinese Test", 50, 50); } </script> </body> </html>
The corresponding display effect is as follows
Blue solid text effect drawn using canvas
Next, we keep other environmental conditions unchanged, and use the strokeText()+strokeStyle
method again to draw the text in the above example. The corresponding JavaScript code is as follows:
<script type="text/javascript"> //Get the Canvas object (canvas) var canvas = document.getElementById("myCanvas"); //Simply detect whether the current browser supports Canvas objects, so as to avoid syntax errors in some browsers that do not support html5 if(canvas.getContext){ //Get the corresponding CanvasRenderingContext2D object (brush) var ctx = canvas.getContext("2d"); //set font style ctx.font = "30px Courier New"; //set font color ctx.strokeStyle = "blue"; //Start drawing text from coordinate point (50,50) ctx.strokeText("CodePlayer+Chinese test", 50, 50); } </script>
We use the browser to visit the page again, and we will see the following display effect (the word "CodePlayer" in the effect picture is actually hollow, but the two sides seem to overlap due to the small font size):
Blue hollow text effect drawn using canvas
expand:
①HTML5画布文字垂直对齐
在HTML5画布中我们使用textBaseline属性来设置对齐方式,对应值如下:
- top
- bottom
- middle
- hanging(挂)
- alphabetic(拼音)
- ideographic
如果你没有设置此属性,默认为:alphabetic
②HTML5画布获取文字度量
在HTML5画布中,使用measureText方法来获取文字的相关度量信息对象,其中包含一个属性,即文字宽度。
基于文字的大小和字体,它可以提供一个准确的文字宽度。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>画布获取文字度量</title> </head> <body> <!-- 添加canvas标签,并加上红色边框以便于在页面上查看 --> <canvas id="gbcanvas" width="550" height="300"></canvas> <script type="text/javascript"> /*Javascript源代码*/ var canvas = document.getElementById('gbcanvas'), // 这里通过gbCanvas获取canvas对象 context = canvas.getContext('2d'); //这里通过canvas获取处理API的上下文context var x = canvas.width/2, y = canvas.height/2 -10; var text = '你好,gbtags.com'; context.font = 'bold 30pt "microsoft yahei"'; context.textAlign = 'center'; context.fillStyle = 'red'; context.fillText( text, x, y); //以下代码获取上面定义text的相关metrics信息 var metrics = context.measureText(text); var width = metrics.width; context.font = '15pt Arial'; context.textAlign = 'center'; context.fillStyle = '#888888'; context.fillText('-' + width + 'px-', x, y +45); </script> </body> </html>
③HTML5画布实现文字折行效果
HTML5画布中,如果需要文字折行效果,需要我们自己书写相关逻辑实现,这里我们可以利用到前面介绍的 measureTex()方法来计算当前文字的宽度,并且和当前能够显示的宽度做比对
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>HTML5 CanvasPattern实现图像平铺的入门示例</title> </head> <body> <!-- 添加canvas标签,并加上红色边框以便于在页面上查看 --> <canvas id="gbcanvas" width="550" height="3020"></canvas> <script type="text/javascript"> var canvas = document.getElementById('gbcanvas'), context = canvas.getContext('2d'); var maxWidth = 500, lineHeight = 30, x = (canvas.width -maxWidth)/2, y = 60 text = '极客所定义一个处理文字折行的方法,使用前面我们介绍,有文字保存到数组'; context.font = 'bold 20pt "microsoft yahei"'; context.fillStyle = '#DD4814'; wrapText(context, text, x, y, maxWidth, lineHeight); /* * 定义一个处理文字折行的方法,使用前面我们介绍的meaureText方法 */ function wrapText(context, text, x, y, maxWidth, lineHeight){ var words = text.split(''); //这里我们将所有文字保存到数组中,注意如果处理英文,请使用split(' '); var line = ''; for(var n = 0; n<words.length; n++){ var testLine = line + words[n]; var metrics = context.measureText(testLine); //Use measureText to calculate width var testWidth = metrics.width; if(testWidth > maxWidth && n>0){ //Here, judge whether the text width exceeds the maximum displayable width context.fillText(line, x, y); line = words[n]; // console.log(line) y += lineHeight; //Set the position of adding text to the next line here }else{ line = testLine; } } context.fillText(line, x, y); } </script> </body> </html>
.