结构
宽高为自定义内容
<canvas canvas-id="html2Img" :style="'height:'+ height +'px;width:'+ width +'px'"></canvas>
~~~
data(){
return{
secondValue:10,
gonext:false,
canvasHidden:true,
width:375,
height:90,
x:0,
y:0,
textStr:'测试文本内容协议内容,相关协议测试文本内容;相关测试文本内容。测试文本内容11协议内容,相关协议测试文本内容;相关测试文本内容。'
}
},
js
主流程
let that = this;
const ctx = uni.createCanvasContext('html2Img');
// 设置背景
this.height = this.getHeight(this.textStr);
ctx.setFillStyle('#ffffff');
ctx.fillRect(0, 0, this.width, this.height);
// 填充文字
ctx.setFillStyle('#000000');
ctx.setFontSize(18);
ctx.setTextAlign('center')
ctx.fillText('标题内容', 187, 30);
ctx.setFontSize(16);
this.drawLongText(ctx,this.textStr);
ctx.draw(false, () => {
uni.canvasToTempFilePath({
x: 0,
y: 0,
canvasId: 'html2Img',
quality: 1,
success: (res) => {
let base64 = 'data:image/jpeg;base64,' + uni.getFileSystemManager().readFileSync(res.tempFilePath, 'base64');
console.log(base64);
},
fail:(err)=>{
console.log(err)
}
}, this)
});
单独封装的换行绘制问题
drawLongText(ctx,str){
let x = 25;
let y = 50;
var lastSubStrIndex = 0; //每次开始截取的字符串的索引
for (let i = 0; i < str.length; i++) {
if (x > 350) {
y += 20; //30为字体的高度
x = 25;
ctx.fillText(str.substring(lastSubStrIndex, i), x, y); //绘制截取部分
}else{
ctx.fillText(str.substring(lastSubStrIndex, i), x, y);
}
x += ctx.measureText(str[i]).width;
if(i == str.length -1){
console.log(lastSubStrIndex + ':' + i)
ctx.fillText(str.substring(lastSubStrIndex+1, i+1), x, y);
}
lastSubStrIndex = i;
}
},
动态设置height高度方法
getHeight(str){
let x = 25;
let y = 60;
for (let i = 0; i < str.length; i++) {
if (x < 350) {
x += 16;
}else{
x = 25;
y += 20;
}
}
y += 30;
return y;
}