html5中的canvas是用于绘制图形的,可以通过 JavaScript 来控制它绘制各种文本和图像,但是在使用 canvas 绘制文字的时候,我们可能想要让这些文字在某处按要求换行,这该如何实现呢?本篇文章将来给大家介绍关于canvas文字换行的方法,话不多说,下面我们来一起看看具体的内容。

在canvas中提供了将文本作为图片输出到画布上的功能,通常用到的函数主要有canvas.drawText 和canvas.fillText两个。

以canvas.fillText()函数为例,在canvas.fillText("information" , width , height , maxwidth )中包含四个参数,"information"表示文本输出的内容,width和height分别表示你想要输出的文本起始字符左上角的位置,而maxwidth则表示了该字符串的最大宽度,例如将maxwidth设为100,则无论字符串有多长,都将限制在100像素宽度内。

接下来我们来看一看将canvas文字换行的代码:

<!DOCTYPE html> <html> <head>   <meta charset="UTF-8">   <title>canvas自动换行</title>   <style type="text/css">     * {       margin: 0     }     #main {       width: 400px;       margin: 20px auto 0;     }     #canvas, #editableWarp, #editable, #hideText {       width: 400px;       height: 125px;       padding: 0;       border: 0;       background: pink;       color: blue;       font-size: 14px;       font-family: 'sans-serif';       position: relative;       z-index: 1     }     #hideText {       z-index: 0;       position: absolute;        word-break: break-word;       word-wrap: break-word;     }     p {       line-height: 32px;     }   </style> </head> <body>   <div id="main">     <p>       输入:     </p>     <div id="editableWarp">       <div id="hideText"></div>       <textarea id="editable" placeholder="请输入文字..."></textarea>     </div>     <p>       canvas输出:     </p>     <canvas id="canvas" width="400" height="125">您的浏览器不支持canvas</canvas>   </div>   <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>   <script type="text/javascript">     var $canvas = $('#canvas'),         $editable = $('#editable'),         $hideText = $('#hideText'),         ctx = $(canvas)[0].getContext("2d");     $editable.keyup(function handleEdittable () {       var txt = $editable.val(),           html = convertText(txt);       $hideText.html(html);       drawText();     });     function convertText(txt) {       var html = txt.replace(/(S)/ig, '<span>$1</span>');       html = html.replace(/n|r/ig, '<br>');       html = html.replace(/s/ig, ' ');       return html;     }     function drawText () {       ctx.clearRect(0, 0, $(canvas).width(), $(canvas).height());       var fontSize = $hideText.css('fontSize');       ctx.font = fontSize + ' sans-serif';       ctx.textAlign = 'conter';       ctx.textBaseline = "top";       ctx.fillStyle = 'red';       $.each($("#hideText span"), function (i, item) {         var pos = $(item).position();         var txt = $(item).text();         ctx.fillText(txt, pos.left, pos.top);       });     }   </script> </body> </html>

canvas换行效果如下:

canvas文字怎么换行?canvas文字换行的方法介绍

本篇文章到这里就结束了,关于canvas元素更多的知识可以参考HTML5开发手册学习具体内容。

标签
DT素材网

DT素材网

144

0

0

( 此人很懒并没有留下什么~~ )