需求:将图片绘制到画布上
非type 2d的绘制
id用来生成画布实例,canvas-id是兼容支付宝小程序
<canvas canvas-id="poster" id="poster" class="poster-box"></canvas>
确保图片加载完成后,才能绘制到画布上,推荐使用.uni.getImageInfo方法,在sucess成功回调函数里进行画布的绘制,获取画布实例的时候第二个参数要加上this
this.ctx = uni.createCanvasContext("poster", this);//这里的this很关键
uni.getImageInfo({
src: "https:xxx",//你的任意图片地址
success: (success) => {
this.path = success.path;//获取到小程序转化获得的路径
this.ctx.drawImage(this.path, 0, 0, 300, 160);//绘制到画布上 后面四个参数都是位置
// this.ctx.save();//如果要画圆形头像 需要save()开头 restore()结尾
// this.ctx.arc(20, 210, 10, 0, 2 * Math.PI); // 将图片绘制到圆上
// this.ctx.strokeStyle = "#fff";
// this.ctx.stroke();
// this.ctx.clip();
// this.ctx.drawImage(this.logo, 10, 200, 20, 20);
// this.ctx.restore();
//data 都是项目的代码 举例一下 string类型传入即可 可以用模板字符串
this.ctx.setFontSize(18);//绘制文字最好设置大小 设置字体颜色 最后插入文字
this.ctx.setFillStyle("#666");
this.ctx.fillText(this.data.position_name, 10, 189);
this.ctx.setFontSize(13);
this.ctx.setFillStyle("#666");
this.ctx.fillText(
`${getCompanyName(this.data.company)}·${this.data.city}`,
10,
215
);
this.ctx.setFontSize(16);
this.ctx.setFillStyle("#007aff");
this.ctx.fillText(
`${this.data.origin_salary}-${
this.data.end_salary
}·${getSalaryTypeName(this.data.salary_type)}`,
170,
189
);
this.ctx.draw(true);// 绘制完成 也很关键的结束代码
console.log("====================================");
console.log("画布生成");
console.log("====================================");
},
fail: (fail) => {
console.log(fail);
},
});
画圆形时候注意
使用clip方法时,画圆步骤的开头要使用save(),restore()结尾,不然会影响后续绘制内容
this.ctx.save();
this.ctx.arc(20, 210, 10, 0, 2 * Math.PI);
// 将图片绘制到圆上
this.ctx.strokeStyle = "#fff";
this.ctx.stroke();
this.ctx.clip();
this.ctx.drawImage(this.logo, 10, 200, 20, 20);
this.ctx.restore();
绘制完成后要保存,使用draw方法,参数一般为true就好
this.ctx.draw(true);
需求:将绘画完成的画布转化成图片,进行后续保存或者显示操作
uni.canvasToTempFilePath() 第二个参数必须为this,否则会报画布找不到的错误
转化成图片也是,前提条件是确认画布已经绘制完成,推荐在draw()里的回调函数中使用转图片的方法,这时候要加上settimeout 进行延迟运行方法,确保图片正常生成
saveImage() {
if (this.tempFilePath) return;
this.ctx.draw(
true,
setTimeout(() => {
console.log("====================================");
console.log("生成图片开始");
console.log("====================================");
uni.canvasToTempFilePath(
{
x: 0,
y: 0,
width: 500,
height: 425,
destWidth: 1000,
destHeight: 850,
canvasId: "poster",
success: (res) => {
// 在H5平台下,tempFilePath 为 base64
console.log(res.tempFilePath);
this.tempFilePath = res.tempFilePath;
this.$emit("update:url", res.tempFilePath);
console.log("图片生成");
},
fail: (err) => {
console.log(err);
},
},
this //canvasToTempFilePath方法的第二个参数 要写this 也很关键
);
}, 500)
);
},