wxml内容 如下
<canvas id="myCanvas" type="2d"
style="width: {{ canvas.width }}px;height: {{ canvas.height }}px;">
</canvas>
<button bindtap="generatePicture">生成图片</button>
JS内容
在 onReady 生命周期拿到canvas实例
data:{
canvas:{ width:150, height:300 },
},
onReady() {
this.createSelectorQuery().select('#myCanvas')
.fields({ node: true, size: true })
.exec((res) => {
this.setData({
canvas: res[0].node
})
})
},
在 点击生成图片 按钮
generatePicture(){
return this.apiPromise('getImageInfo', { src: 图片路径 })
.then(e=>{
const canvas = this.data.canvas
const { screenWidth, screenHeight } = wx.getSystemInfoSync()
const { width, height } = e
const multipleH = height/screenHeight
const multipleW = width/screenWidth
if(width/multipleH>screenWidth){
canvas.width = width/multipleW
canvas.height = height/multipleW
}else {
canvas.width = width/multipleH
canvas.height = height/multipleH
}
this.setData({
canvas,
})
return this.drawImage(this.data.canvas)
})
},
往canvas里绘制图片,绘制完成执行 drawText()
drawImage({width, height}){
return new Promise(resolve=>{
const ctx = this.data.canvas.getContext('2d')
const img = this.data.canvas.createImage()
img.src = this.data.originUrl
img.onload = () => {
ctx.drawImage(img, 0, 0, width, height)
resolve(this.drawText(ctx, width, height))
}
})
},
往canvas里绘制图片,绘制完成执行 drawText()
drawText(ctx, width, height){
const values = [{
color:'red',
size:18,
x:0,
y:0,
text:'测试文字',
}]
values.forEach(item=>{
ctx.fillStyle = item.color
ctx.font = `${item.size}px sans-serif`
ctx.fillText(item.text, item.x, item.y)
})
return this.exportCanvasImage(width, height)
},
使用 canvasToTempFilePath Api 导出图片 res.tempFilePath
为图片路径
exportCanvasImage(width, height){
return this.apiPromise('canvasToTempFilePath',{
canvas: this.data.canvas,
width,
height,
})
.then(res=>{
return res.tempFilePath
})
},
一个小轮子, 将wx api转为promise
apiPromise(api, arg = {}){
return new Promise((resolve, reject) => {
const success = arg.success
const fail = arg.success
arg.success = (e) => {
resolve(e)
success?.apply(this, e)
}
arg.fail = (e) => {
reject(e)
fail?.apply(this, e)
}
wx[api](arg)
})
}