微信小程序分享给好友 以及下载到图库
最终实现效果
- 页面布局代码
<!--components/share/share.wxml-->
<view class="share-box">
<view wx:if="{{isShow}}" class="panel">
<view class="canvas">
<canvas canvas-id="shareCanvas" class="share"></canvas>
</view>
<view class="btn-box">
<view class="btn-panel">
<view class="share-friend">
<button open-type="share">
<view class="img-box">
<image src="../../static/wachat.png"></image>
</view>
分享好友
</button>
</view>
<view class="share-down" bindtap="downCanavs">
<view class="img-box">
<image src="../../static/down.png"></image>
</view>
保存相册
</view>
</view>
</view>
</view>
</view>
css样式
/* components/share/share.wxss */
.panel { //遮罩层样式
position: fixed;
top: 0;
bottom: 0;
right: 0;
left: 0;
background-color: #333333;
display: flex;
align-items: flex-end;
align-content: center;
z-index: 888;
}
.share-box {
position: relative;
}
.canvas {
width: 100%;
position: absolute;
top: 100rpx;
left: 0;
right: 0;
z-index: 9999;
}
.share {
width: 600rpx;
height: 800rpx;
margin: 0 auto;
background-color: #629fb6;
}
.btn-box{
position: absolute;
bottom: 0;
background-color:#fff;
left: 0;
right: 0;
width: 100%;
height: 200rpx;
}
.btn-panel{
padding: 0 80rpx;
display: flex;
justify-content: space-between;
align-items: center;
}
.share-friend,.share-down{
width: 100%;
text-align: center;
line-height: 160rpx;
font-size: 26rpx;
}
.share-friend button{
width: auto;
font-weight: normal;
background-color: #fff;
font-size: 26rpx;
}
.btn-panel .img-box{
width: 64rpx;
height: 64rpx;
margin: 0 auto;
}
.img-box image{
width: 100%;
height: 100%;
vertical-align: middle;
}
js代码
- 获取设备宽高 便于计算 小程序码是直接写死的 在本地 直接拿
isShow: true,
img: '../../static/code.jpg', //需要画到画布上的小程序码
windowWidth: wx.getSystemInfoSync().windowWidth, //设备屏幕宽度
windowHeight: wx.getSystemInfoSync().windowHeight //获取当前设备屏幕高度
- 获取画布大小 然后开始画 x,y 轴位置自己计算
canvasPanel(){ //开始画
const ctx = wx.createCanvasContext('shareCanvas');
ctx.rect(0, 0, this.data.windowWidth, this.data.windowHeight);
ctx.setFillStyle('#fff');
ctx.fill()
//画文字
ctx.setFillStyle('#629fb6')
ctx.fillRect(0, 0, this.data.windowWidth, 70) //
ctx.setFontSize(20)
ctx.setFillStyle("#fff")
let str = '布业电子色卡'
ctx.fillText(str, this.data.windowWidth * 0.25, 70 * 0.6)
//画图片
ctx.drawImage(this.data.img, (this.data.windowWidth - 250) / 2 * 0.5, this.data.windowHeight / 250 + 120, 250, 250)
ctx.draw();
},
- 将画布的内容下载到相册
downCanavs() { //下载画布
wx.canvasToTempFilePath({
x: 0,
y: 0,
width: this.data.windowWidth,
height: this.data.windowWidth,
destWidth: this.data.windowWidth * 3, //值越大 像素越清晰
destHeight: this.data.windowHeight * 3,
canvasId: 'shareCanvas', //绑定画布id
success(res) {
console.log(res.tempFilePath)
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success(res) {
wx.showToast({
title: '保存成功!',
})
}
})
}
})
},