我试图获取图片的数据网址。该图像来自一个跨越原始的远程服务器,维基百科。我使用这个JavaScript来尝试这样做:
# get the image
const img = document.createElement('img')
img.src = 'https://upload.wikimedia.org/wikipedia/commons/thumb/2/26/Strychnine.svg/360px-Strychnine.svg.png'
# don't send credentials with this request
img.crossOrigin = 'anonymous'
# now copy to a <canvas /> to get data URL
const canvas = document.createElement('canvas')
canvas.width = img.width
canvas.height = img.height
const ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0)
canvas.toDataURL('image/jpg')
但我收到此错误:Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported
。
我读到这是一个CORS问题。如果服务器没有设置Access-Control-Allow-Origin
标头,浏览器会阻止您从图像中获取图像数据。 但这是奇怪的事情。我检查了响应,并设置了标题 。所以我不明白为什么这不起作用。这是我从终端发出请求时的输出(标题与Chrome devtools中显示的相同)。
$ http 'https://upload.wikimedia.org/wikipedia/commons/thumb/2/26/Strychnine.svg/360px-Strychnine.svg.png'
HTTP/1.1 200 OK
Accept-Ranges: bytes
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: Age, Date, Content-Length, Content-Range, X-Content-Duration, X-Cache, X-Varnish
Age: 6359
Connection: keep-alive
Content-Disposition: inline;filename*=UTF-8''Strychnine.svg.png
Content-Length: 11596
Content-Type: image/png
Date: Fri, 29 Dec 2017 21:00:31 GMT
Etag: 223fb180fc10db8693431b6ca88dd943
Last-Modified: Sun, 04 Sep 2016 09:13:24 GMT
Strict-Transport-Security: max-age=106384710; includeSubDomains; preload
Timing-Allow-Origin: *
Via: 1.1 varnish-v4, 1.1 varnish-v4, 1.1 varnish-v4, 1.1 varnish-v4
X-Analytics: https=1;nocookies=1
X-Cache: cp1049 hit/4, cp2022 pass, cp4026 hit/4, cp4024 hit/3
X-Cache-Status: hit-front
X-Client-IP: 2606:6000:670c:f800:989:be22:e59d:3c3f
X-Object-Meta-Sha1Base36: 1xx5tvhafvp54zfrfx5uem0vazzuo1a
X-Timestamp: 1472980403.52438
X-Trans-Id: tx154e595e211c449d95b3d-005a469417
X-Varnish: 474505758 476375076, 160459070, 709465351 725460511, 931215054 920521958
那为什么这不起作用?我的画布需要 else 才能被污染&#34;?
答案 0 :(得分:4)
当您在图片上设置src
时,浏览器会请求图片。但到那时,您还没有设置img.crossOrigin
。将img.crossOrigin
行移到img.src
行上方。
修复了受污染的画布问题,但您仍然无法获取您的网址。对图像的请求是异步的。您正尝试使用尚未加载的图像绘制到画布。将其余代码移到图片上的load
处理程序中,并将img.src
行放在最后,以完成所有操作:
const img = document.createElement('img');
img.crossOrigin = 'anonymous';
img.addEventListener('load', () => {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
console.log(canvas.toDataURL('image/jpg'));
});
img.src = 'https://upload.wikimedia.org/wikipedia/commons/thumb/2/26/Strychnine.svg/360px-Strychnine.svg.png';