js代码
async getImage (url,width, height) {
const off = wx.createOffscreenCanvas({type:'2d'})
const image = off.createImage()
await new Promise((resolve, reject)=>{
image.onload = resolve
image.src = url
})
return image
},
aaa(){
const now = new Date();
const year = now.getFullYear();
const month = now.getMonth() + 1;
const day = now.getDate();
const date = `${year}年${month}月${day}日`;
const no = `F${year}182006`;
const that=this;
wx.createSelectorQuery().select('#myCanvas').fields({ node: true, size: true }).exec((cres) => {
console.log(cres);
var rect = cres[0]
console.log(rect)
var textCanvas = rect.node
var ctx = textCanvas.getContext('2d')
that.getImage("../../images/card.jpg",800,1000).then(image=>{
ctx.drawImage(image, 0, 0,1000,800)
})
ctx.font ='28px';
ctx.fillStyle='#000';
ctx.fillText(`同志在 ${year} 年 1 月 1 日至 ${month} 月 ${day} 日参加了`, 240, 380);
ctx.fillText(`编号:${no}`,170 , 640);
ctx.fillText(`${date}`, 670, 640);
wx.canvasToTempFilePath({
canvas:textCanvas,
success: (res) => {
console.log('成功生成临时文件路径:', res.tempFilePath);
wx.downloadFile({
url: res.tempFilePath,
success: (downloadRes) => {
if (downloadRes.statusCode === 200) {
console.log(downloadRes)
wx.saveFile({
tempFilePath: downloadRes.tempFilePath,
success: (saveRes) => {
console.log(saveRes)
console.log('证书保存路径:', saveRes.savedFilePath);
wx.showToast({
title: '证书下载成功',
icon: 'success',
});
},
fail: (err) => {
wx.showToast({
title: '证书下载失败'+err,
icon: 'none',
});
},
});
}
},
fail: (err) => {
wx.showToast({
title: '证书下载失败'+err,
icon: 'none',
});
console.log(err);
},
});
},
fail: (err) => {
console.error('生成临时文件路径失败:', err);
wx.showToast({
title: '证书生成失败',
icon: 'none',
});
},
});
})
},
wxml:
<canvas id="myCanvas" type="2d" style="width:1000px;height:800px"></canvas>
结果:
做个代码片段吧
还有,看到你demo 里边写的感觉你是新老版本的canvas 写法混用了,你用的是新版Canvas 2D,但是还用了旧版本的CanvasContext