canvas实现文字自动换行,段落居中,单行的时候居中方法,主要用到以下方法:
/****绘制自动换行的字符串****/
//ctx_2d getContext("2d") 对象
//lineheight 段落文本行高
//bytelength 设置单字节文字一行内的数量
//text 写入画面的段落文本
//startleft 开始绘制文本的 x 坐标位置(相对于画布)
//starttop 开始绘制文本的 y 坐标位置(相对于画布)
//ctx_fillStyle 字体颜色
//ctx_font 字体
//istrue 是否设置
function writeTextOnCanvas(ctx_2d, lineheight, bytelength, text ,startleft, starttop,ctx_fillStyle,ctx_font,istrue){
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;
}
if(text.length<17 && istrue==1){
ctx_2d.textAlign="center";
}else{
if(istrue==1){
ctx_2d.textAlign="";
startleft=130;
}
}
for(var i = 1; getTrueLength(text) > 0; i++){
var tl = cutString(text, bytelength);
ctx_2d.fillStyle= ctx_fillStyle; //字体颜色
ctx_2d.font= ctx_font; //字体
ctx_2d.fillText(text.substr(0, tl).replace(/^\s+|\s+$/, ""), startleft, (i-1) * lineheight + starttop);
text = text.substr(tl);
}
}调用方法:
let canvas = document.createElement('canvas')
canvas.width = "608"
canvas.height = "1080" //创建画布,并设置宽高
let ctx = canvas.getContext("2d")
var ctName = "我是文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字"
// 对象 - 行高 - 文字一行内的数量 -文本 - x 坐标位置 -y
writeTextOnCanvas(ctx,30,500,ctName,263,979,'#fff','normal 18px Microsoft YaHei',0); //名字 +头衔说明:这个方法采用设置文字区块的宽度,来达到文字版块居中,另一方面考虑文字不到一行的情况下,通过以下方法判断,给文字加居中选项
if(text.length<17 && istrue==1){
ctx_2d.textAlign="center";
}else{
if(istrue==1){
ctx_2d.textAlign="";
startleft=130;
}
}此判断文字个数是否达到指定个数,达到的话就移除textAlign="center"文字居中属性,否则就增加textAlign="center"属性,并设置距离y轴距离。