使用html2Canvas生成图片跨域如何处理?
1.出现跨域的情况
这种情况只会出现在html2Canvas需生成的海报中的图片与当前环境不在同一个域下
2.解决方案
处理跨域,将接口返回的url处理为base64再进行处理或者后端直接返回base64
3.如何将url转换为base64?(利用canvas的toDataURL属性将url转为base64)
function getImageBase64Data(imgSrc) {
function getBase64(img) {
let canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
let ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
let dataURL = canvas.toDataURL('image/jpeg');
return dataURL;
}
let baseUrl = new Promise(function (resolve, reject) {
let image = new Image();
image.crossOrigin = '*'; // 图片处理跨域
if (imgSrc.indexOf('data:image/jpeg;base64') > -1) {
image.src = imgSrc + '?v=' + Math.random(); // 处理图片从缓存获取
} else {
image.src = imgSrc;
}
image.onload = function () {
let imageBase64Data = getBase64(image);
resolve(imageBase64Data);
}
});
return baseUrl;
}
4.使用html2Canvas生成海报
const download = () => {
let content = document.getElementById('promote-content');
if (content) {
html2canvas(content, { useCORS: true, allowTaint: true }).then(res => {
const imgBase64 = res.toDataURL('image/jpeg');
let link = document.createElement('a');
link.style.display = 'none';
link.href = imgBase64;
link.setAttribute('download', name + moment().format('YYYYMMDDHHmm'));
document.body.appendChild(link)
link.click();
document.body.removeChild(link)
})
}
}