Page({
data: {
},
onLoad: function (options) {
wx.createSelectorQuery()
.select('#canvasCheck')
.fields({
node: true,
size: true,
})
.exec(this.init.bind(this))
},
onReady: function () {
},
init(res) {
res[0].node.width = res[0].node._width
res[0].node.height = res[0].node._height
const canvas = res[0].node
console.log(res[0].node._height)
const ctx = canvas.getContext('2d')
this.drawPoster(canvas, ctx)
},
async drawPoster(canvas, ctx) {
//绘制背景
ctx.beginPath()
ctx.lineWidth = 4
ctx.moveTo(222, 2);
ctx.arcTo(684, 2, 684, 40, 20); //右上角圆弧
ctx.lineTo(684, 626)
ctx.arcTo(664, 626, 664, 648, 20); //左边圆弧
ctx.arcTo(664, 672, 688, 672, 20); //左边圆弧
ctx.lineTo(684, 800)
ctx.arcTo(684, 820, 656, 820, 20); //右下角圆弧
ctx.lineTo(22, 820)
ctx.arcTo(2, 820, 2, 800, 20); //左下角圆弧
ctx.lineTo(2, 674)
ctx.arcTo(20, 674, 20, 652, 20); //左边圆弧
ctx.arcTo(20, 630, 0, 628, 20); //左边圆弧
ctx.lineTo(2, 22)
ctx.arcTo(2, 2, 21, 2, 20); //左上角圆弧
ctx.lineTo(222, 2)
ctx.closePath()
ctx.strokeStyle = '#000'
ctx.fillStyle = '#fff'
ctx.fill()
ctx.stroke()
ctx.save()
//插入-大图片
ctx.beginPath()
ctx.moveTo(11, 236)
ctx.lineTo(675, 236)
ctx.lineTo(675, 620)
ctx.arcTo(655, 620, 655, 640, 20);
ctx.lineTo(31, 640)
ctx.arcTo(31, 620, 11, 620, 20);
ctx.closePath()
ctx.clip();
const img = await new Promise((resolve, reject) => {
let canvasImg = canvas.createImage()
canvasImg.src = 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2F48124ed00ae163228d4e65acf0d54c5cc5a2f31a2e142-PaXGuD_fw658&refer=http%3A%2F%2Fhbimg.b0.upaiyun.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1632464066&t=cdd3247f22e65b792f64a5dbfdd76d9b'
canvasImg.onload = () => {
resolve(canvasImg)
}
})
ctx.drawImage(img, 8, 236, 670, 410)
ctx.restore()
const query = wx.createSelectorQuery();
const canvasObj = await new Promise((resolve, reject) => {
query.select('#canvasCheck')
.fields({ node: true, size: true })
.exec(async (res) => {
resolve(res[0].node);
})
});
wx.canvasToTempFilePath({
canvas: canvasObj, //现在的写法
destWidth: 686,
destHeight: 822,
success: res => {
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: (res) => {
wx.showToast({
title: '保存成功',
icon: 'success',
duration: 2000
})
},
fail: (err) => {
wx.getSetting({
success: (res) => {
if (!res.authSetting['scope.writePhotosAlbum']) {
this.setData({
showtotast: true
})
}
}
})
}
})
},
fail: err => {
console.log(err)
wx.showToast({
title: '海报生成失败,请稍后再试',
icon: 'none',
duration: 2000
})
},
complete: () => {
wx.hideLoading()
}
}, this);
},
})
效果图