Home > Web Front-end > H5 Tutorial > HTML5-8 __Canvas text

HTML5-8 __Canvas text

黄舟
Release: 2017-02-18 14:38:05
Original
1678 people have browsed it

The canvas API has powerful text functions. The canvas text can be manipulated in the same way as other path objects: the text outline can be drawn and the interior of the text can be filled.

The text drawing of the context object is implemented by two functions:

fillText(text, x, y, maxwidth);

strokeText(text, x, y, maxwidth);                                                                                                                

#strokeText(text, x, y, maxwidth); The coordinate parameter, maxwidth is an optional parameter, used to limit the font size and force the text font to shrink to the specified size.<br>There is also a measureText() function, which will return a measurement object, which contains Specify the actual display width of text in the current context

<br>
Copy after login
在HTML5.js 源码定义为:
Copy after login
/**@param {string} text@return {TextMetrics}*/CanvasRenderingContext2D.prototype.measureText = function(text) {};
Copy after login
<br>

An example

<!DOCTYPE html>
<html>
  <meta charset="UTF-8">
  <title>Canvas 文本</title>
  <canvas id="trails" style="border: 1px solid;"  width="400" height="300"> </canvas>
  <script>
        function drawTrails() {
            var canvas = document.getElementById(&#39;trails&#39;);
            var context = canvas.getContext(&#39;2d&#39;);
            // 在canvas 上绘制标题文本
            context.save();
            // 字号为60px,  字体为impact
            context.font = "60px impact";
            // 将文本填充为棕色
            context.fillStyle = &#39;#996600&#39;;
            // 将文本设为居中对齐
            context.textAlign = &#39;center&#39;;
            // 在canvas顶部中央的位置
            // 以大字体的形式显示文本
            context.fillText(&#39;Happy Trails!&#39;, 200, 60, 400);
            context.restore();
        }
        window.addEventListener("load", drawTrails, true);
  </script>
</html>
Copy after login
<br>

, replace fillText in the code with strokeText(), the effect is: <br>

<br>

In order to ensure that the text is read in each browser It can be displayed normally under any browser. The Canvas API provides CSS-like properties for the context to ensure that the actual display effect is highly configurable.

<br><br>

above It is the content of HTML5-8 __Canvas text. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!

<br>

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template