blog
blog copied to clipboard
解决canvas,toDataURL跨域问题
图片服务器需要配置Access-Control-Allow-Origin
设置通配符,允许任何域名访问
header("Access-Control-Allow-Origin: *");
指定域名
header("Access-Control-Allow-Origin: www.xxx.com");
此时,Chrome浏览器不会有Access-Control-Allow-Origin相关的错误信息,但是,还会有其他的跨域错误信息。
HTML crossOrigin属性解决资源跨域问题
在HTML5中,有些元素提供了CORS(Cross-Origin Resource Sharing)
属性,这些元素包括,
因此,上面的跨域问题可以这么处理:
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.crossOrigin = 'anonymous';
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
resolve(canvas.toDataURL());
};
img.src = url;
其中,只要crossOrigin
的属性值不是use-credentials
,全部都会解析为anonymous,包括空字符串。
url 加时间戳,清空缓存
如果上面还是没有解决跨域问题,那么要考虑图片是否被浏览器缓存住了。
没有加时间戳的请求
加上时间戳的请求
因此,代码可以这么写
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
resolve(canvas.toDataURL());
};
img.src = url + '?time=' + new Date().valueOf();