项目里使用到用canvas生成海报,在toDataURL报了这个错误Tainted canvases may not be exported。
原因就在于使用了跨域的图片,所以说是被污染的画布。
解决方案如下
1】为image请求添加跨域
var image = new Image() image.setAttribute("crossOrigin",'Anonymous') image.src = src
但也许有可能服务器不让你跨域请求图片(也不知道为啥),那么用到方案2
2】通过把请求的图片转化成base64再进行使用
代码如下
function getURLBase64(url) { return new Promise((resolve, reject) => { var xhr = new XMLHttpRequest() xhr.open('get', url, true) xhr.responseType = 'blob' xhr.onload = function() { if (this.status === 200) { var blob = this.response var fileReader = new FileReader() fileReader.onloadend = function(e) { var result = e.target.result resolve(result) } fileReader.readAsDataURL(blob) } } xhr.onerror = function() { reject() } xhr.send() }) }
