开发过程中需要根据商品信息生成海报,供用户下载海报 、分享海报等
效果:
1.首先搭建页面结构:
<!-- 按钮结构 -->
<view class="share flex">
<u-icon name="scan" size="20" @click="drawPic"></u-icon>
<u-icon name="share" size="20" @click="shareWeixin"></u-icon>
分享
</view>
<!-- 海报画布 -->
<view class="canvasBox" v-if="showPoster">
<text class="close" @click="showPoster = false">x</text>
<canvas style="width: 220px;height: 340px;" class="canvas" canvas-id="mycanvas"></canvas>
<view class="btmBox">
<view class="item">
<u-icon name="weixin-fill"></u-icon>
<view style="font-size:12px" @click="shareImg">分享好友</view>
</view>
<view class="item">
<u-icon name="coupon"></u-icon>
<view style="font-size:12px" @click="saveImage">保存海报</view>
</view>
</view>
</view>
2.js控制用户点击二维码按钮后,弹出dialog展示海报内容:
methods: {
//绘制海报
drawPic() {
this.showPoster = true
uni.showLoading({
title: '正在生成海报'
})
let myCanvas = uni.createCanvasContext('mycanvas', this)
// 封面标题
myCanvas.font = '12px Arial'
myCanvas.fillText('鹏程监测 APT', 110, 30)
// 封面图
myCanvas.drawImage(this.imgList[1], 30, 40, 170, 170)
// 价格
myCanvas.font = ` 14px Arial`
myCanvas.fillStyle = 'blue'
myCanvas.fillText('¥ 150', 30, 220)
myCanvas.font = `10px Arial`
myCanvas.fillStyle = '#9C9C9C'
myCanvas.fillText('原价:¥0.00', 80, 220)
myCanvas.font = `14px Arial`
myCanvas.fillStyle = '#000'
myCanvas.fillText('外观监测', 30, 240)
// 分享码
myCanvas.drawImage(this.imgList[1], 150, 280, 50, 50)
//长按识别购买
myCanvas.font = '10px Arial'
myCanvas.fillStyle = '#9C9C9C'
myCanvas.fillText('长按识别或保存图片', 30, 310)
//开始绘画,必须调用这一步,才会把之前的一些操作实施
myCanvas.draw(false, res => {
uni.canvasToTempFilePath({
canvasId: 'mycanvas',
success: res => {
console.log(res, 'draw')
uni.hideLoading()
this.poster = res.tempFilePath
this.showPoster = true
},
fail: err => {
console.log(err, 'fail')
uni.hideLoading()
uni.showToast({
title: '名片加载失败',
duration: 2000
})
}
})
})
},
//点击保存
saveImage() {
var _this = this
uni.showLoading({
title: '正在生成图片...'
})
uni.saveImageToPhotosAlbum({
filePath: _this.poster,
success(res) {
console.log(res, 'downlaod')
uni.hideLoading()
uni.showModal({
title: '保存成功',
content: '图片已成功保存到相册,快去分享到您的圈子吧',
showCancel: false
})
}
})
},
// 分享--展示大图
shareImg() {
uni.previewImage({
current: 0,
urls: [this.poster]
})
},
// 分享到微信好友
shareWeixin() {
const _that = this
uni.showLoading({
title: '努力加载中...'
})
uni.share({
provider: 'weixin',
scene: 'WXSceneSession', //分享到聊天界面
type: 5, //分享为小程序
imageUrl: _that.poster, //png地址
title: '',
miniProgram: {
//type为5必选
id: '', //微信小程序原始id
path: '', //点击链接进入的页面
type: 0, //微信小程序版本类型,可取值: 0-正式版; 1-测试版; 2-体验版。 默认值为0。
webUrl: '' //兼容低版本的网页链接
},
success: res => {
console.log(res, 'share')
uni.hideLoading()
showToast({
title: '分享成功',
icon: 'none'
})
}
})
}
}