这种情况只会出现在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/jpegbase64') >-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)
})
}
}
前端web开发html避免js的跨域访问的方法是后台服务端做域配置兼容处理。1、在server端请求过滤的时候加入以下控制:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
Access-Control-Allow-Origin这个属性配置成*就表示接受任何域过来的请求
2.ajax中请求如下:
$.ajax({
xhrFields: {
withCredentials: true
},
data:{ my: 'a' },
url: 'http://MyApp/Page', 这里是跨域访问
type: 'POST'
})