Method of controlling font display and rendering using HTML5 canvas API

Time:2021-7-25

API introduction
Today we begin to fight for a new content – the text API of HTML5 canvas! You know, artists are usually also calligraphers, so we should learn to write and write beautiful words. Isn’t it interesting?

OK, let’s preview what canvas text APIs are.

attribute describe
font Sets or returns the current font property of the text content
textAlign Sets or returns the current method for text content
textBaseline Sets or returns the current text baseline used when drawing text

method describe
fillText() Draw the filled text on the canvas
strokeText() Draw text on canvas (no fill)
measureText() Returns an object containing the specified text width

After reading the above table, I believe the children’s shoes have a general understanding. Here, we first talk about the display and rendering of text, using font, filltext() and stroketext().

Basic text display
When using text on canvas, you must first know that the text on canvas cannot use CSS style. Although the font attribute is similar to the CSS attribute, it cannot be used interchangeably.

Display text three-step strategy:

1. Use font to set font.
2. Use fillStyle to set the font color.
3. Use the filltext() method to display the font.
The font attribute here can not be specified. If no font is specified, 10px sans serif will be used automatically by default.

The following code simply displays a piece of text

JavaScript CodeCopy contents to clipboard
  1. <!DOCTYPE html>   
  2. <html lang=“zh”>   
  3. <head>   
  4.     <meta charset=“UTF-8”>   
  5. < title > basic text display < / Title >
  6.     <style>   
  7.         body { background: url(“./images/bg3.jpg”) repeat; }  
  8.         #canvas { border: 1px solid #aaaaaa; display: block; margin: 50px auto; }   
  9.     </style>   
  10. </head>   
  11. <body>   
  12. <div id=“canvas-warp”>   
  13.     <canvas id=“canvas”>   
  14. Your browser doesn’t support canvas?! Change one quickly!!
  15.     </canvas>   
  16. </div>   
  17.   
  18. <script>   
  19.     window.onload = function(){   
  20.         var canvas = document.getElementById(“canvas”);   
  21.         canvas.width = 800;   
  22.         canvas.height = 600;   
  23.         var context = canvas.getContext(“2d”);   
  24.         context.fillStyle = “#FFF”;   
  25.         context.fillRect(0,0,800,600);   
  26.   
  27.         //1.   Use ‘font’ to set the font.  
  28.         context.font = “50px serif”;   
  29.         //2.   Use ‘fillStyle’ to set the font color.  
  30.         context.fillStyle = “#00AAAA”;   
  31.         //3.   Use the ‘filltext()’ method to display the font.  
  32.         context.fillText(“《CANVAS–Draw on the Web》”,50,300);   
  33.   
  34.     };   
  35. </script>   
  36. </body>   
  37. </html>  

Operation results:
2016324112147710.jpg (850×500)

Set text font font font
It is very easy to set the font style in canvas. The font format of font attribute is the same as that of CSS, so you only need to apply the string compatible with CSS to the font attribute. You can set font style, font variation, font thickness, font size and line height, font appearance, etc.

The basic format is as follows.

CSS CodeCopy contents to clipboard
  1. context.font =    
  2. “[font-style] [font-variant] [font-weight]   
  3. [font-size/line-height] [font-family]”  

The above five parameters can be defaulted, and the parameters are separated by commas.

Tip: the parameter is wrapped in brackets [] to indicate that it can be defaulted.
The following describes the meaning of these parameter values.

font-style
The font style property defines the style of the font.

value describe
normal Default value. The browser displays a standard font style.
italic The browser displays an italic font style.
oblique The browser displays an italic font style.

The latter two usually look no different. But the way to get the tilt effect is not the same. Italic uses italics in the font library. Usually, a font library has the italics and bold forms of the font. Oblique directly tilts the font. If a font library does not have italics, italic cannot be used. If you want to obtain a tilted font, you can only use oblique.

font-variant
The font variant property sets the font of small uppercase letters to display text, which means that all lowercase letters will be converted to uppercase, but all letters using small uppercase fonts have a smaller font size than the rest of the text.

value describe
normal Default value. The browser displays a standard font style.
small-caps The browser displays a font of small uppercase letters.

Look at the picture below to see what this attribute means.
2016324112239497.jpg (522×242)

That’s it. The upper line uses the default value normal, and the lower line uses small caps. The effect is that the original uppercase English letters remain unchanged, and the lowercase English letters become uppercase, but the size remains unchanged.

font-weight
The font weight property sets the thickness of the text.

value describe
normal Default value. The browser displays a standard font style.
bold Bold character definition.
bolder Define thicker characters.
lighter Define finer characters.
Value between 100-900 Defines characters from thick to thin. 400 is equivalent to normal and 700 is equivalent to bold.

font-size
Font size property can set the font size.

value describe
xx-samll Minimum font
x-small Smaller font
samll Small font.
medium Default value.
large Large font.
x-large Large font.
xx-large Large font.
Arbitrary value The unit PX represents the font size value

line-height
The line height property sets the distance between rows (row height). Negative values are not allowed

font-family
Font family specifies the font family of the element.

Use @ font face to customize fonts
HTML5 supports common fonts. If not, you can use @ font face to expand fonts. However, it is not recommended.

@Font face can load the font file on the server side and let the client display the fonts not installed on the client. At present, EOT and TTF files can be loaded.

Example: the code is too long, slightly XD
2016324112305009.jpg (850×500)

The font library I downloaded here only has 26 uppercase English letters A-Z, so it automatically converts lowercase to uppercase when encountering Chinese characters or numbers. It specifies to use star symbols instead. Is it cool to use @ font face in CSS3 to customize fonts.

Text Rendering
Like drawing a rectangle, there are two ways to “draw” text — filltext() and stroketext(). The reason why they are the same is that these two methods can also set the corresponding properties through fillStyle and strokestyle. As mentioned earlier, color filling, gradient filling and even pattern filling are all possible.

The parameter tables of filltext() and stroketext() are the same. They accept four parameters, namely string, x, y and maxlen, where string refers to the string to be displayed, followed by X and Y refers to the displayed coordinates, and the last maxlen is a numerical parameter that can be defaulted, representing the maximum width of the display in pixels. If the length of the text exceeds this maxlen, canvas will compress the displayed text horizontally. Usually, in order to ensure the beauty of the font, we do not set maxlen.

That is, context.filltext (string, x, y, [maxlen]) and context.stroketext (string, x, y, [maxlen]).

Let’s take a case to see the effect of text rendering.

JavaScript CodeCopy contents to clipboard
  1. <!DOCTYPE html>   
  2. <html lang=“zh”>   
  3. <head>   
  4.     <meta charset=“UTF-8”>   
  5. < title > text rendering < / Title >
  6.     <style>   
  7.         body { background: url(“./images/bg3.jpg”) repeat; }  
  8.         #canvas { border: 1px solid #aaaaaa; display: block; margin: 50px auto; }   
  9.     </style>   
  10. </head>   
  11. <body>   
  12. <div id=“canvas-warp”>   
  13.     <canvas id=“canvas”>   
  14. Your browser doesn’t support canvas?! Change one quickly!!
  15.     </canvas>   
  16. </div>   
  17.   
  18. <script>   
  19.     window.onload = function(){   
  20.         var canvas = document.getElementById(“canvas”);   
  21.         canvas.width = 800;   
  22.         canvas.height = 600;   
  23.         var context = canvas.getContext(“2d”);   
  24.         context.fillStyle = “#FFF”;   
  25.         context.fillRect(0,0,800,600);   
  26.   
  27.         context.beginPath();   
  28.         context.font = “50px Verdana”;   
  29.         var gradient = context.createLinearGradient(0,0,800,0);   
  30.         gradient.addColorStop(“0”,“magenta”);   
  31.         gradient.addColorStop(“0.5”,“blue”);   
  32.         gradient.addColorStop(“1.0”,“red”);   
  33.         context.fillStyle = gradient;   
  34.         context.strokeStyle = “#00AAAA”;   
  35.         context.strokeText(“airingursb.github.io”, 50, 100);   
  36.         context.fillText(“airingursb.github.io”, 50, 200);   
  37.   
  38.         //Limit width  
  39.         context.fillText(“airingursb.github.io”, 50, 300, 200);   
  40.   
  41.         context.beginPath();   
  42.         var img = new Image();   
  43.         img.src = “./images/bg1.jpg”;   
  44.         img.onload = function(){   
  45.             var pattern = context.createPattern(img, “repeat”);   
  46.             context.fillStyle = pattern;   
  47.             context.fillText(“airingursb.github.io”, 50, 400);   
  48.         }   
  49.   
  50.         context.beginPath();   
  51.         context.fillStyle = “#00AAAA”;   
  52.         context.fillText(“Airing’s blog, welcome to”, 50, 500);   
  53.     };   
  54. </script>   
  55. </body>   
  56. </html>  

Operation results:
2016324112330747.jpg (850×500)

Here, the first line uses the stroketext () method of general color, the second line uses the filltext () method of gradient color, the third line sets maxlen, the fourth line fills the font with texture pattern, and the fifth line is advertising

Recommended Today

Implementation example of go operation etcd

etcdIt is an open-source, distributed key value pair data storage system, which provides shared configuration, service registration and discovery. This paper mainly introduces the installation and use of etcd. Etcdetcd introduction etcdIt is an open source and highly available distributed key value storage system developed with go language, which can be used to configure sharing […]