<template>
<view>
<canvas canvas-id="canvas4renovate":style="{ windowWidth + 'px', height: windowWidth * 1.77 + 'px'}" style="letter-spacing: -1rpx;" v-show="!needLongTapSaveImg"></canvas>
<image :src="tempFilePath" :style="{ windowWidth + 'px', height: windowWidth * 1.77 + 'px'}" v-show="needLongTapSaveImg"></image>
<button type="default" @click="downLoadImg()">保存至相册</button>
</view>
</template>
<script>
export default {
data() {
return {
renovationInfo: {},
windowWidth: 0,
windowHeight: 0,
tempFilePath: '',
needLongTapSaveImg: false,
}
},
onLoad(options) {
this.renovationInfo = JSON.parse(options.apply);
uni.getSystemInfo({
success: (res) => {
this.windowWidth = res.windowWidth;
this.windowHeight = res.windowHeight;
this.createImg();
}
})
},
methods: {
createImg: function(){
const ctx = uni.createCanvasContext('canvas4renovate');
ctx.drawImage('/static/images/permiss.jpg', 0, 0, this.windowWidth, this.windowWidth * 1.77);
ctx.font = 'bold 16rpx serif';
ctx.setTextAlign('left');
ctx.setFillStyle('#5A3834');
ctx.fillText('编号:' + this.renovationInfo.rId, this.windowWidth * 0.13, this.windowWidth * 1.77 * 0.44);
ctx.fillText('单位:' + this.renovationInfo.company, this.windowWidth * 0.13, this.windowWidth * 1.77 * 0.505);
ctx.fillText('负责人:' + this.renovationInfo.personMain, this.windowWidth * 0.13, this.windowWidth * 1.77 * 0.57);
ctx.fillText('联系电话:' + this.renovationInfo.tel, this.windowWidth * 0.13, this.windowWidth * 1.77 * 0.63);
ctx.font = 'bold 12rpx serif';
ctx.fillText('有效期:' + this.renovationInfo.startTimeView + '至' + this.renovationInfo.endTimeView, this.windowWidth * 0.14, this.windowWidth * 1.77 * 0.83);
ctx.fillText('公司:XXX', this.windowWidth * 0.14, this.windowWidth * 1.77 * 0.86);
ctx.draw(true, () => {
setTimeout(() => {
uni.canvasToTempFilePath({
canvasId: 'canvas4renovate',
fileType: 'jpg',
success: (res) => {
this.tempFilePath = res.tempFilePath
//#ifdef H5
this.needLongTapSaveImg = true;
//#endif
}
})
})
})
},
downLoadImg: function() {
if(this.tempFilePath == ''){
uni.showToast({
title: '图片未生成',
icon: 'none'
})
return;
}
//#ifndef H5
uni.saveImageToPhotosAlbum({
filePath: this.tempFilePath,
success: function() {
uni.showToast({
title: '已保存至相册',
icon: 'none'
})
}
});
//#endif
//#ifdef H5
uni.showToast({
title: '请长按图片-保存至相册'
})
//#endif
}
}
}
</script>
<style>
</style>
【注】
一。 1.77 为 背景图的高宽比
二。 canvas画布 的 style 属性中的width和height 做数据绑定, 宽带为当前使用者手机的宽度, 高度为手机宽度 * 1.77, 维持背景图的宽高比例
三。 由于目前H5端不支持saveImageToPhotosAlbum直接保存至图库的接口,所以H5端使用长按图片保存至手机的方法
四。 由于canvas画布不可以长按保存,所以针对H5端在页面布局上添加一个image标签, 其src即为canvasToTempFilePath返回的tempFilePath
五。 needLongTapSaveImg 用来控制canvas画布 与 H5端长按图片 的显示切换, 只有当平台是H5时,显示Image标签,隐藏canvas画布, 这样用户可以长按保存; 除了H5的其他平台则直接调用saveImageToPhotosAlbum
1