在用IDEA时,调用getImageData()报跨域的错误,原因是图片存储在本地时,是默认没有域名的,用getImageData方法时,浏览器会判定为跨域而报错。
搜索了很多方法尝试解决,包括:
- 设置时间戳
var img = new Image();
var url = 'https://media.prod.mdn.mozit.cloud/attachments/2013/06/22/5397/7a3ec0cae64a95ad454ac3bc2c71c004/rhino.jpg';
img.src = url + '?' + new Date().getTime();
img.setAttribute('crossOrigin', '');
https://blog.youkuaiyun.com/leftfist/article/details/106947101
- 设置crossOrigin属性并修改浏览器设置
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var img = new Image();
img.crossOrigin = ''; //这里!!!
img.onload = function () {
context.drawImage(this, 0, 0);
context.getImageData(0, 0, this.width, this.height);
};
img.src = 'https://vip.itzlm.cn/images/canvas.jpg';
https://www.cnblogs.com/happy-8090/p/11244056.html
- 更改浏览器设置: --allow-file-access-from-files 或 --disable-web-security
https://blog.youkuaiyun.com/w5167839/article/details/45485645
2、3操作也并行试过了,不知道是不是操作问题,始终不得行。。
最终的解决方案是,使用VsCode,下载一个叫Live Server的插件:
然后在右下角启用它:
打开html文件的时候,在VsCode中右键点击 Open With Live Server:
就可以啦!
非常非常简单!
https://blog.youkuaiyun.com/weixin_41056807/article/details/109533221