canvas
1.思路:之前第一次接触到这个功能需求的时候,第一时间是去官网完文档。懵懵懂懂的就去怼代码。还在网上找了好多的demo看,但是后面实现出来的效果,终究不是自己理想的,后面经过2天我总有做出了,下面给大家分享一下我在绘画中遇到的问题和解决的办法,希望可以帮到你们。
先看看我的小程序页面

1.微信 wxml 别忘看来要写canvas-id
<view class='downPic' bindtap='saveImg'>
<image src='../image/xiazai.png'></image>
<canvas
canvas-id="secondCanvas" style='width:375px;height:603px;background-color:#ffffff;position:absolute;left:-1000px;'>
</canvas>
</view>
2.
saveImg:function(e){
var that =this;
console.log(11);
const ctx = wx.createCanvasContext('secondCanvas');
let path1 = this.data.img1;
let path2 = this.data.img2;
let path3 = this.data.img3;
console.log(path1);
console.log(path2);
console.log(path3);
ctx.rect(0,0,650,910);
ctx.fillStyle = "#ffffff";
ctx.fill();
ctx.drawImage(path1, 20, 20, 335,180);
ctx.drawImage(path2, 140, 258, 100, 90);
ctx.setFontSize(12);
ctx.fillStyle = "#888888";
ctx.fillText(this.data.tip, 140, 369, 200);
ctx.drawImage(path3, 150, 388, 80, 80);
ctx.setFontSize(14);
ctx.fillStyle = "#ffa42b";
ctx.fillText(this.data.user_name, 168, 495, 100,);
ctx.setFontSize(14);
ctx.fillStyle = "#666666";
ctx.fillText(this.data.tuijian, 158, 530, 100);
ctx.setFontSize(14);
ctx.fillStyle = "#333333";
ctx.fillText(this.data.courseInfo.course_name, 108, 560, 200);
ctx.draw(false,()=>{
wx.canvasToTempFilePath({
x: 0,
y: 0,
destWidth: 375 * 2,
destHeight: 663 * 2,
canvasId: 'secondCanvas',
fileType: 'png',
success: function (res) {
console.log(res)
console.log(res.tempFilePath);
let imgUrl = res.tempFilePath;
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: function (res) {
wx.showToast({
title: '成功保存到相册',
icon: 'success'
})
}
})
}
})
但是我用真机测试保存到手机

可以看到这里的头像是没有显示的
因为canvas只能用本地路径和临时路径,网络图片通过下载转换成临时路径,再绘制到canvas上,这样基本ok了。
onReady: function () {
var that=this;
wx.downloadFile({
url: that.data.courseInfo.course_pic,
success(res) {
if (res.statusCode==200){
that.setData({
img1: res.tempFilePath
})
}
}
})
wx.downloadFile({
url: that.data.qr_image,
success(res) {
if (res.statusCode==200){
that.setData({
img2: res.tempFilePath
})
}
}
})
console.log(that.data.head_img);
wx.downloadFile({
url: that.data.head_img,
success(res) {
if (res.statusCode==200){
console.log(res.tempFilePath)
that.setData({
img3: res.tempFilePath
})
}
}
})
},