这个迭代有个小东西有一点小难度,就是下面这个合成图
![](https://img.haomeiwen.com/i14199926/879f6cd9996c2aa7.png)
背景图片中心加上一个图标。
接下来实现:
首先定义这两个图片,需要注意的是 不能使用本地图片。
<canvas class="canvas" canvas-id="share" style="width: 500rpx; height: 400rpx;"/>
data() {
return {
img: 'https://vky-test-oss.inboyu.com/upload/39ef7d0a-8b26-4a3c-801f-d32135cea3bd.png',
icon: 'https://vky-test-oss.inboyu.com/upload/39ef5e72-b6ab-3048-56f4-421899d79cf9.png',
img2: ''
}
}
methods: {
getImageInfo(url) {
return new Promise((resolve, reject) => {
wx.getImageInfo({
src: url,
success: resolve,
fail: reject
})
})
},
draw() {
const avatarPromise = this.getImageInfo(this.icon)
const backgroundPromise = this.getImageInfo(this.img)
Promise.all([avatarPromise, backgroundPromise])
.then(([avatar, background]) => {
const ctx = wx.createCanvasContext('share', this)
const canvasWidth = 250
const canvasHeight = 200
const avatarWidth = 40
const avatarHeight = 40
ctx.drawImage(background.path, 0, 0, canvasWidth, canvasHeight)
ctx.drawImage(
avatar.path,
canvasWidth / 2 - avatarWidth / 2,
canvasHeight / 2 - avatarHeight / 2,
avatarWidth,
avatarHeight
)
ctx.draw(true, () => {
wx.canvasToTempFilePath({
x: 0,
y: 0,
width: 250,
height: 200,
destWidth: 250 * 6,
destHeight: 200 * 6,
canvasId: 'share',
success: res1 => {
this.img2 = res1.tempFilePath
},
fail: res1 => {
Utils.showToast(res1)
}
})
})
})
}
}
以上两个方法,第一个getImageInfo 主要是返回图片的本地路径,用于下面的drawImage。
第二个方法draw 很简单,就是初始化画布,并画图。
主要是需要等待两个图片都要获得本地地址才能画图
const avatarPromise = this.getImageInfo(this.icon)
const backgroundPromise = this.getImageInfo(this.img)
Promise.all([avatarPromise, backgroundPromise])
.then(([avatar, background]) => {
const ctx = wx.createCanvasContext('share', this)
还要注意的是:const ctx = wx.createCanvasContext('share', this) 这一句 需要写在then里边。我曾试过放在Promise.all前面,画出来的是一片空白。
最后完美画出来了。
不过等我在手机上预览的时候,发现图片很模糊。
后来尝试把生成图片的大小放大几倍就清晰了。
![](https://img.haomeiwen.com/i14199926/400115d3fe87056f.png)
到此为止,坑就填完了!
网友评论