1. 下载html2canvas
<-- npm -->
npm i html2canvas --save
<-- yarn -->
yarn add html2canvas
2. 下载image-tools
<-- npm -->
npm i image-tools --save
<-- yarn -->
yarn add image-tools
3. 在插件市场下载html2canvas组件
也可以使用下面代码
<template>
<view>
<view class="html2canvas" :prop="domId" :change:prop="html2canvas.create">
<slot></slot>
</view>
</view>
</template>
<script>
import { base64ToPath } from 'image-tools.js';
export default {
name: 'html2canvas',
props: {
domId: {
type: String,
required: true
}
},
methods: {
async renderFinish(base64) {
try{
const imgPath = await base64ToPath(base64, '.jpeg');
this.$emit('renderFinish', imgPath);
}catch(e){
//TODO handle the exception
console.log('html2canvas error', e)
}
},
showLoading() {
uni.showToast({
title: "正在生成海报",
icon: "none",
mask: true,
})
},
hideLoading() {
uni.hideToast();
}
}
}
</script>
<script module="html2canvas" lang="renderjs">
import html2canvas from 'html2canvas';
export default {
methods: {
async create(domId) {
try {
this.$ownerInstance.callMethod('showLoading', true);
const timeout = setTimeout(async ()=> {
const shareContent = document.querySelector(domId);
const canvas = await html2canvas(shareContent,{
width: shareContent.offsetWidth,//设置canvas尺寸与所截图尺寸相同,防止白边
height: shareContent.offsetHeight,//防止白边
logging: true,
useCORS: true
});
const base64 = canvas.toDataURL('image/jpeg', 1);
this.$ownerInstance.callMethod('renderFinish', base64);
this.$ownerInstance.callMethod('hideLoading', true);
clearTimeout(timeout);
}, 500);
} catch(error){
console.log(error)
}
}
}
}
</script>
4. 插件市场uQRCode
二维码生成插件,不需要的刻意忽略
5. 在文件中使用
<template>
<view class="page">
<view class="container">
<html2canvas ref="html2canvas" :domId="domId" @renderFinish="renderFinish">
<view class="img" id="image">
<text>生成图片</text>
//生成二维码(不需要刻意不要)
<canvas id="qrcodes" canvas-id="qrcodes" />
</view>
</html2canvas>
<image :src="img"></image>
</view>
</view>
</template>
<script>
import uQRCode from '@/components/uqrcode/common/uqrcode.js'
import html2canvas from '@/components/html2canvas/html2canvas.vue'
import { base64ToPath, pathToBase64 } from 'image-tools.js';
export default{
components:{
html2canvas
},
data(){
return{
img: '',
domId: ''
}
},
onReady() {
//生成二维码
uQRCode.make({
componentInstance: this,//绑定this指向
canvasId: 'qrcodes',//画布标识
size: 40,//二维码尺寸
backgroundColor: '#ffffff',//背景色
foregroundColor: '#000',//前景色
fileType: 'png',//输出图片类型
errorCorrectLevel: uQRCode.errorCorrectLevel.H,//纠错等级
text: '123'//二维码内容
})
.then(res => {
console.log(res)
})
},
onLoad(){
this.domId = '#image'
},
methods:{
renderFinish(filePath) {
console.log(filePath)
this.img = filePath;
}
}
}
</script>
<style lang="scss" scoped>
uni-canvas{
width: 80rpx;
height: 80rpx;
}
</style>
遇到问题解决
使用oss服务器里的图片报跨域:
- 在oss服务器配置所有可访问限制
Access-Control-Allow-Origin '*'
如果是接口请求的显示出来的图片,叫后台在图片链接后面加上个后缀,比如时间戳?t=1234567