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 placeholder="请输入文字..."></textarea>
</div>
<p>
canvas输出:
</p>
<canvas 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换行效果如下:
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /boutique/detail/tanfjkcf
系列文章
更多
同类精品
更多
-
photoshop保存的图片太大微信发不了怎么办
PHP中文网 06-15 -
Android 11 保存文件到外部存储,并分享文件
Luke 10-12 -
word里面弄一个表格后上面的标题会跑到下面怎么办
PHP中文网 06-20 -
《学习通》视频自动暂停处理方法
HelloWorld317 07-05 -
微信公众号没有声音提示怎么办
PHP中文网 03-31 -
photoshop扩展功能面板显示灰色怎么办
PHP中文网 06-14 -
excel下划线不显示怎么办
PHP中文网 06-23 -
怎样阻止微信小程序自动打开
PHP中文网 06-13 -
excel打印预览压线压字怎么办
PHP中文网 06-22 -
photoshop蒙版画笔没反应怎么办
PHP中文网 06-24