问题描述 前端图片跨域
---->修改源码: img.src = src + ‘?t=’ + new Date().getTime();
前端—> 封装一个html2canvas组件
<template>
<view class="html2canvas" :prop="domId" :change:prop="html2canvas.create">
<slot></slot>
</view>
</template>
<script>
export default {
name: 'html2canvas',
props: {
domId: {
type: String,
required: true
}
},
methods: {
async renderFinish(base64) {
try{
this.$emit('renderFinish', base64);
}catch(e){
this.$emit('renderFinish', "err");
//TODO handle the exception
}
},
showLoading() {
uni.showToast({
title: "正在生成图片",
icon: "none",
mask: true,
duration: 100000
})
},
hideLoading() {
uni.hideToast();
}
}
}
</script>
<script module="html2canvas" lang="renderjs">
import html2canvas from 'html2canvas';
export default {
methods: {
async create(domId) {
if(!domId) return;
try {
const _this = this;
const timeout = setTimeout(async ()=> {
const shareContent = document.querySelector(domId);
let width = shareContent.offsetWidth;
let height = shareContent.offsetHeight;
let _canvas = document.createElement("canvas");
let scale = 2; //定义任意放大倍数 支持小数
_canvas.width = width * scale; //定义canvas 宽度 * 缩放
_canvas.height = height * scale; //定义canvas高度 *缩放
let context = _canvas.getContext("2d"); //获取context,设置scale
context.translate(0, 0);
const canvas = await html2canvas(shareContent,{
logging: true,
async: false,
useCORS: true, // 【重要】开启跨域配置
allowTaint: false,//允许跨域图片
taintTest: false,//是否在渲染前测试图片
backgroundColor:"#746F6C",
canvas: _canvas,
width:width, //dom 原始宽度
height:height ,//dom 原始高度
scale:scale, // 添加的scale 参数
proxy:'https://file.zhenqingkongjian.com/'
});
console.log(canvas)
const base64 = canvas.toDataURL('image/jpeg');
console.log(base64)
this.$ownerInstance.callMethod('renderFinish', base64);
clearTimeout(timeout);
}, 500);
} catch(error){
this.$ownerInstance.callMethod('renderFinish',"err");
}
},
}
}
</script>
<style lang="scss">
</style>