wx.createCanvasContext()的api已经停止更新,开始我也用的这个,部分手机不兼容(我丢),于是更换成wx.createSelectorQuery()
1.wxml,根据ui设计的图片背景图设置宽高
<canvas type="2d" style="width: 420rpx;height:340rpx; opacity: 0;z-index: -1; position: absolute;top: -900px;" id="canvasId"></canvas>
2.js,title标题,imgurl背景图片,city城市,type描述,colors颜色控制
`
//分享图卡片绘制
canvFn(that,title,imgurl,city,type,colors){
wx.getSystemInfo({
success: (result) => {
let pixelRatio=result.pixelRatio||2 // 获取设备像素比
let screen_width= result.windowWidth/375
let query=wx.createSelectorQuery().in(that);
query.select('#canvasId').fields({
node: true,
size: true,
}).exec((res)=>{
var b=pixelRatio
var width = res[0].width //获取画布宽度
var height = res[0].height //获取画布高度
const ctx= res[0].node
const canvas = ctx.getContext('2d')
that.setData({
canvasObj: ctx,
height: ctx.height
})
ctx.width = width* pixelRatio
ctx.height = height* pixelRatio
// 绘制背景图
let imsg = imgurl
const codeImg = ctx.createImage();//创建图片画布
codeImg.src = imsg;
codeImg.onload = () => {
canvas.drawImage(codeImg, 0, 0, ctx.width, ctx.height);//将图片绘制到canvas画布上
canvas.restore(); //恢复之前保存的绘图上下文状态 可以继续绘制
// 绘制背景图
canvas.beginPath()
canvas.font = `normal normal ${20*pixelRatio}px sans-serif`;
canvas.fillStyle = colors.title
canvas.textAlign='center'
canvas.fillText(title, ctx.width/2, 56*b);
canvas.beginPath()
canvas.stroke()
canvas.font = `normal normal ${14*pixelRatio}px sans-serif`;
canvas.textAlign='center'
city&&canvas.fillText('-'+city+'-', ctx.width/2, 85*b);
type&&canvas.fillText('('+type+')', ctx.width/2, city?105*b:85*b);
// canvas.draw(false, ()=>{
wx.canvasToTempFilePath({
x: 0,
y: 0,
canvas: that.data.canvasObj,
success: function (res) {
console.log(res)
//这里是自己封装的腾讯云上传接口,调用拿到https://xxxxxx图片路径
cosImg((res)=>{
that.setData({
shareMain:res.content
})
},'',res.tempFilePath)
//这里是自己封装的腾讯云上传
// console.log(res.tempFilePath)
// canvasToTempFilePath = res.tempFilePath // 返回的图片地址保存到一个全局变量里
// that.setData({
// showShareImg: true
// })
// wx.showToast({
// title: '绘制成功',
// })
},
fail: function () {
// wx.showToast({
// title: '绘制失败',
// })
},
complete: function () {
// wx.hideLoading()
}
})
// },that)
}
});
// })
},
})
},`
最终实现