- 需求点击生成二维码海报(点击后跳转到qr海报页面)
- renderjs 调用 HTML2canvas
- 生成base64后转为临时路径,保存到手机相册
<template>
<view class="poster">
<!-- @click="html2canvas.create" -->
<view ref="qrPoster" id="qrPoster" class="poster-image"
:style="{'backgroundImage': 'url('+posterImageSrc+') '}">
<!-- <image :src="posterImageSrc" mode="widthFix" v-show="false" @load="html2canvas.create"></image> -->
<image ref="qrImage" id="qrImage" :src="qrImageSrc" @load="html2canvas.create" mode="widthFix">
</image>
<!-- <image ref="qrImage" id="qrImage" :src="qrImageSrc" mode="widthFix"></image> -->
<!-- <image v-if="imageUrl" :src="qrImageSrc" mode="widthFix"></image> -->
</view>
<!-- <canvas canvas-id="myCanvas" width="300" height="600"></canvas> -->
</view>
</template>
<script>
import html2canvas from 'html2canvas';
import {
navigation
} from '@dcloudio/uni-app-plus';
import {
Log
} from "@icon-park/vue";
export default {
data() {
return {
tempImagePath: "",
imageUrl: '', // 图片的 URL
posterImageSrc: "",
qrImageSrc: "",
}
},
onLoad({
src
}) {
this.posterImageSrc = JSON.parse(src)
this.getQr()
},
mounted() {
// html2canvas(document.querySelector('.poster-image'), setup).then((canvas) => {
// console.log(canvas, 'canvas');
// document.body.appendChild(canvas); // 自动在下方显示绘制的canvas图片
// });
// this.creatImg()
// this.exportPicture()
// console.log(this.$refs.qrImage.$el);
// this.$refs.qrImage.$el.onload = function() {
// console.log('onload');
// this.capturePage()
// }
},
methods: {
getQr() {
this.$u.api.getQr().then(res => {
console.log(res);
this.qrImageSrc = res.data.ewmUrl
})
},
toQrPoster() {
uni.navigateTo({
url: "/pages/sys/task/qrPoster?base64=" + JSON.stringify(this.base64)
})
},
capturePage() {
const targetElement = this.$refs.qrPoster.$el; // 需要生成图片的元素,此处表示当前页面的根元素
console.log('capturePage');
html2canvas(targetElement).then(canvas => {
console.log('将 Canvas 转换为图片');
// 将 Canvas 转换为图片
// const dataUrl = canvas.toDataURL('image/png');
const dataUrl = canvas.toDataURL();
// 更新图片的 URL
this.imageUrl = dataUrl;
console.log(dataUrl, 'dataUrl');
navigation.createDownload({
mediaUri: dataUrl,
title: 'imageName',
description: 'Save image to gallery',
mimeType: 'image/png',
success: () => {
uni.showToast({
title: '图片保存成功',
duration: 2000,
});
},
fail: (err) => {
uni.showToast({
title: '图片保存失败',
duration: 2000,
icon: 'none',
});
console.error(err);
},
});
});
},
onImageLoad() {
this.creatImg()
},
// 生成图片
creatImg() {
html2canvas(document.getElementById('qrPoster'), {
width: dom.offsetWidth, //设置canvas尺寸与所截图尺寸相同,防止白边
height: dom.offsetHeight, //防止白边
logging: true,
useCORS: true,
allowTaint: true,
scale: window.devicePixelRatio,
dpi: 300,
scrollY: 0
}).then((canvas) => {
const link = canvas.toDataURL("image/jpg");
console.log(link, 'link');
this.exportPicture(link);
});
},
// 导出图片
exportPicture(link, name = "网络营系统二维码海报" + new Date().getTime()) {
const file = document.createElement("a");
file.style.display = "none";
file.href = link;
file.download = decodeURI(name);
document.body.appendChild(file);
file.click();
document.body.removeChild(file);
},
renderFinish(opt) {
uni.hideLoading()
this.base64 = opt.path
this.save()
},
showLoding() {
this.isShowPoster = true
uni.showLoading({
title: '图片生成中'
})
},
hideLoading() {
uni.hideLoading()
},
// 保存图片
save() {
console.log('save');
// uni.canvasToTempFilePath({
// canvasId: "myCanvas",
// success: (res) => {
// this.tempFilePath = res.tempFilePath;
// console.log('success', res);
// uni.saveImageToPhotosAlbum({
// filePath: res.tempFilePaths,
// success: function() {
// console.log('saveImageToPhotosAlbum success');
// },
// fail: (error) => {
// console.log('转换为临时路径失败:', error);
// }
// });
// },
// fail: (error) => {
// console.log('转换为临时路径失败:', error);
// }
// });
// return
let that = this;
const bitmap = new plus.nativeObj.Bitmap("test")
bitmap.loadBase64Data(this.base64, function() {
const url = "_doc/" + new Date().getTime() + ".png"; // url为时间戳命名方式
bitmap.save(url, {
overwrite: true, // 是否覆盖
// quality: 'quality' // 图片清晰度
}, (i) => {
uni.saveImageToPhotosAlbum({
filePath: url,
success: function() {
// that.base64 = url
// that.toQrPoster()
uni.showToast({
title: '图片保存成功',
icon: 'none'
})
bitmap.clear()
}
});
}, (e) => {
console.log(e);
uni.showToast({
title: '图片保存失败',
icon: 'none'
})
bitmap.clear()
});
}, (e) => {
uni.showToast({
title: '图片保存失败',
icon: 'none'
})
bitmap.clear()
})
},
}
}
</script>
<script module="html2canvas" lang="renderjs">
import html2canvas from 'html2canvas'
export default {
mounted() {
// this.create()
},
methods: {
create() {
this.$ownerInstance.callMethod('showLoding', true) // this.$ownerInstance.callMethod用于两个script之间交流
const timer = setTimeout(async () => {
try {
const dom = document.getElementById('qrPoster')
const canvas = await html2canvas(dom, {
width: dom.offsetWidth, //设置canvas尺寸与所截图尺寸相同,防止白边
height: dom.offsetHeight, //防止白边
logging: true,
useCORS: true,
allowTaint: true,
scale: window.devicePixelRatio,
dpi: 300,
scrollY: 0
})
// const base64 = canvas.toDataURL('image/png');
// canvas.setAttribute("canvas-id", 'myCanvas');
// document.body.appendChild(canvas);
// console.log('canvas:', canvas, base64)
// const file = document.createElement("a");
// file.style.display = "none";
// file.href = base64;
// file.download = decodeURI(name);
// document.body.appendChild(file);
// file.click();
// document.body.removeChild(file);
this.$ownerInstance.callMethod('renderFinish', {
path: canvas.toDataURL('image/png', 1.0)
})
clearTimeout(timer)
} catch (e) {
this.$ownerInstance.callMethod('hideLoading', true)
console.log(e)
}
}, 1000)
}
}
}
</script>
<style>
.poster-image {
padding: 20rpx;
box-sizing: border-box;
text-align: center;
width: 100vw;
height: 100vh;
background-size: cover;
/* background-position: 100%; */
}
.poster-image image {
position: absolute;
bottom: 80rpx;
right: 80rpx;
width: 200rpx;
height: 200rpx;
}
</style>
<style lang="scss">
.poster-image {
text-align: center;
}
// .poster-image image {
// width: 100%;
// height: 85vh;
// }
.generatePoster {
display: flex;
justify-content: space-around;
width: 100%;
position: absolute;
bottom: 20rpx;
}
</style>