效果图:
找了好多文章都会报错:小程序绘画时出现 getCanvasHandlers is not defined-最后查看https://blog.csdn.net/weixin_46743083/article/details/125658200 该文章-才处理解决
这个选择低版本号就不会报错了
<template>
<view class="content">
<!-- 这个是绘制图像的画布 -->
<canvas canvas-id="myCanvas" class="myCanvas"></canvas>
<!-- 这个是绘制好的图片 -->
<image show-menu-by-longpress="true" class="shareImg" v-if="shareImg" :src="shareImg"></image>
</view>
</template>
<script>
export default {
data() {
return {
//绘制好的图片临时路径,其他地方可以直接使用
shareImg: false,
}
},
onLoad() {
uni.hideTabBar(); //不让底部显示tab选项
//这里去请求接口获取到二维码地址和邀请码
uni.showLoading({
title:"加载中..."
})
//例如请求获取结果未下方
let data = {
ewmUrl:'http://www.vsincoop.com/static/gzh.2a5048db.png',//二维码路径
// ewmUrl:'',//二维码路径
yqmCode:"F2EDR5",//邀请码
}
//这块支持小程序条件编译
// #ifndef APP-PLUS || H5
wx.showShareMenu({
menus: ['shareAppMessage', 'shareTimeline']
});
this.drawShareImg(data);
// #endif
},
//转发给朋友
onShareAppMessage(res) {
return {
title: '转发给朋友标题',
path: '/pages/index',//这是跳转路径
imageUrl: this.shareImg
}
},
//转发朋友圈
onShareTimeline(res) {
return {
title: '转发朋友圈标题',
path: '/pages/index',//这是跳转路径
imageUrl: this.shareImg
}
},
methods: {
//绘制图片
drawShareImg(data) {
let that = this;
uni.downloadFile({
url: data.ewmUrl,
success: function(res) {
//这个是绘制比例,按设计图宽度750则为1
let r = 1;
const ctx = uni.createCanvasContext('myCanvas')
//注意:这块图片是相对路径,你项目根据具体情况看写几个../
ctx.drawImage("../static/my/bg.png", 0, 0, 750 / r, 1334 / r);
ctx.drawImage("../static/my/lg.png", 258 / r, 0, 230 / r, 88 / r);
ctx.drawImage("../static/my/yh.png", 18 / r, 190 / r, 694 / r, 373 / r);
ctx.setFontSize(36 / r)
ctx.setFillStyle('#FFFFFF')
ctx.fillText('我的邀请码:'+data.yqmCode, 210 / r, 580 / r)
ctx.drawImage(res.tempFilePath, 240 / r, 620 / r, 270 / r, 270 / r);
ctx.setFontSize(26 / r)
ctx.setFillStyle('#FFFFFF')
ctx.fillText('长按识别二维码', 274 / r, 944 / r)
ctx.draw(true, function() {
//需要延迟以防绘制黑屏阶段
setTimeout(() => {
uni.canvasToTempFilePath({
quality:1,
x: 0,
y: 0,
width: 750 / r,
height: 1344 / r,
destWidth: 750 / r,
destHeight: 1344 / r,
canvasId: 'myCanvas',
success: function(rd) {
//绘制成功赋值
that.shareImg = rd.tempFilePath;
uni.hideLoading()
}
})
}, 50);
})
}
});
}
}
}
</script>
<style scoped lang="scss">
.content {
width: 100vw;
height: 100vh;
position: relative;
.shareImg {
width: 100%;
height: 100%;
display: block;
}
.myCanvas {
position: absolute;
z-index: -100;
left: -10000px;
top: -10000px;
width: 750px;
height: 1334px;
}
}
</style>