html5文档换行,HTML5 canvas 文本自动换行

HTML5 canvas 文本自动换行

调用:

var my_cvs = document.getElementById("my_cvs"); var ctx_2d = my_cvs.getContext("2d"); writeTextOnCanvas(ctx_2d,30,24,'文字内容文字内容文字内容文字内容',182,607);

函数:

//ctx_2d getContext("2d") 对象

//lineheight 段落文本行高

//bytelength 设置单字节文字一行内的数量

//text 写入画面的段落文本

//startleft 开始绘制文本的 x 坐标位置(相对于画布)

//starttop 开始绘制文本的 y 坐标位置(相对于画布)

function writeTextOnCanvas(ctx_2d, lineheight, bytelength, text ,startleft, starttop){

function getTrueLength(str){//获取字符串的真实长度(字节长度)

var len = str.length, truelen = 0;

for(var x = 0; x < len; x++){

if(str.charCodeAt(x) > 128){

truelen += 2;

}else{

truelen += 1;

}

}

return truelen;

}

function cutString(str, leng){//按字节长度截取字符串,返回substr截取位置

var len = str.length, tlen = len, nlen = 0;

for(var x = 0; x < len; x++){

if(str.charCodeAt(x) > 128){

if(nlen + 2 < leng){

nlen += 2;

}else{

tlen = x;

break;

}

}else{

if(nlen + 1 < leng){

nlen += 1;

}else{

tlen = x;

break;

}

}

}

return tlen;

}

for(var i = 1; getTrueLength(text) > 0; i++){

var tl = cutString(text, bytelength);

ctx_2d.fillText(text.substr(0, tl).replace(/^\s+|\s+$/, ""), startleft, (i-1) * lineheight + starttop);

text = text.substr(tl);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值