canvas:canvas绘制海报中文字自动换行
问题描述
canvas绘制的海报在某一行文字过多时不会自动换行(设置文本宽度无用)
源代码
context.fillText(this.data.goods.package_brief, 17 * getRatio(), 350 * getRatio());
新方法调用
this.drawText(context, this.data.goods.package_brief,17*getRatio(),340*getRatio(),200);
解决方法
drawText: function (context,t,x,y,w){
var chr = t.split("");
var temp = "";
var row = [];
for (var a = 0; a < chr.length; a++) {
if (context.measureText(temp).width < w && context.measureText(temp + (chr[a])).width <= w) {
temp += chr[a];
}//context.measureText(text).width 测量文本text的宽度
else {
row.push(temp);
temp = chr[a];
}
}
row.push(temp);
// 只显示2行,加...
if (row.length>=2){
for (var b = 0; b < 2; b++) {
var str = row[b];
console.log(row, str)
if (b == 1) {
str = str.substring(0, str.length) + '...';
}
context.fillText(str, x, y + (b + 1) * 15);
}
}else{
for (var b = 0; b < row.length; b++) {
context.fillText(row[b], x, y + (b + 1) * 15);//字体20,间隔24。类似行高
}
}
}
参数详解:
drawText: function (context,t,x,y,w){}中 context是canvas自身,t是要转换的文字,x是距离canvas左边的距离,y是距离canvas顶部的距离,w是设定的文字内容宽度