```
```js
function setCanvas(DOMID) {
let img = document.getElementById(DOMID).querySelector('img')
document.body.appendChild(convertImageToCanvas(img))
}
```
很显然,报错
#### 栗子2
本地标签内设置跨域允许选项, `web-server`未设置跨域允许选项
这次连图片都出不来,直接报错
这个好理解,浏览器[同源策略](https:/https://img.qb5200.com/download-x/developer.mozilla.org/zh-CNhttps://img.qb5200.com/download-x/docs/Web/Security/Same-origin_policy)限制嘛
Access to image at 'xxxx' (redirected from 'xxxx') from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
```
**居然可以了**,但是~如果在代码内设置跨域呢?
### 栗子5
```js
function setCanvas(DOMID) {
let img = document.getElementById(DOMID).querySelector('img')
img.crossOrigin= 'anonymous'
document.body.appendChild(convertImageToCanvas(img))
}
```
**报错**
我看[官方文档](https:/https://img.qb5200.com/download-x/developer.mozilla.org/zh-CNhttps://img.qb5200.com/download-x/docs/Web/API/HTMLImageElement/crossOrigin)的意思是必须同步设置`crossOrigin=anonymouse`,该图片凭证才会被信任
*This means that CORS is enabled and credentials are sent if the image is fetched from the same origin from which the document was loaded.*
否则缓存的图像数据仍然会被画布视为有污染的跨源内容.
怎么办?重新取一遍图片呗,加个随机数,图片还是那个图片,不过加了个马甲,浏览器就不认识了
### 栗子6
```js
function setCanvas(DOMID) {
let img = document.getElementById(DOMID).querySelector('img')
img.src =img.src+'?v='+Math.random()
img.crossOrigin= 'anonymous'
img.onload=()=>{
document.body.appendChild(convertImageToCanvas(img))
}
}
```
**binggo**, 完美解决
所以我们在开发过程中,新建图片,更换图片,还原图片等功能代码内,最好每一次都加个随机数,以保证源都是最新的,不走缓存
-----
多说一点吧,关于`fabric.js`的相关跨域配置见下方
```js
let _fabricConfig = {
// ....
crossOrigin:'anonymous'
};
/* fabric对象 */
let _fabricObj = new fabric.Canvas(id, _fabricConfig);
// 新建图片对象时
let imgInstance = new fabric.Image.fromURL(url + '?v='+ Math.random(), img => {}, {crossOrigin: 'anonymous'})
// 动态更新图片时
let currentActive = _fabricInstance.getActiveObj();
currentActive.setSrc(randomURL, img =>{}, {crossOrigin: 'anonymous'})
```