一、问题描述
今天在做公众号的时候,使用html2canvas生成海报,截图的内容中有张图片是网络路径,直接报错,跨域了,截完后的图,少了那张图片是网络路径的。
在网上看了一些前端转base64的方法,但是在在前端转的时候也直接遇到跨域的问题。
加了 image.setAttribute(“crossOrigin”, “anonymous”);没用
网络路径后面加个随机变量也没用。然后打算写了服务器demo,在服务器端直接转成base64,试试。
二、写个node服务器
安装两个模块express mime-types
全部代码
//创建一个简单的web服务器
const fs = require('fs')
const path = require('path');
const express = require('express')
const mineType = require("mime-types");
var app = express()
app.use('/public/', express.static('./public/'))
var base64img = function (file) {
let filePath = path.resolve(file);
let data = fs.readFileSync(path.resolve(filePath));
data = new Buffer(data).toString('base64');
return 'data:' + mineType.lookup(filePath) + ';base64,' + data;
}
// 当get请求/路径时 浏览器写入的地址,当按下回车键后,请求方式默认是get请求,只有在ajax中的表单自己定义为post请求才是post请求
app.get('/image', function (req, res) {
// 1、允许跨域
res.header('Access-Control-Allow-Origin', '*')
// 2、允许哪些方法访问
res.header('Access-Control-Allow-Methods', 'get,post')
var data = base64img("public/weima.jpg")
res.send(data)
res.end()
})
app.listen(9527, function () {
console.log('express app is runing...')
})
服务器目录
三、前端使用
请求
async createCode() {
await axios.get("http://192.168.78.137:9527/image").then((res) => {
console.log(res.data);
this.qrcode = res.data;
setTimeout(() => {
this.html2canvas();
}, 300);
});
},
截图
html2canvas() {
var domObj = this.$refs.poster;
html2canvas(domObj, {
useCORS: true,
allowTaint: false,
logging: false,
letterRendering: true,
backgroundColor: null,
scale: window.devicePixelRatio,
}).then((canvas) => {
// 在微信里,可长按保存或转发
this.$toast.clear();
this.posterImg = canvas.toDataURL("image/png");
console.log("this.posterImg", this.posterImg);
this.showShare = true;
});
},
结果
可以避免跨域,也可以截图
生成的base64
页面
截取的图片