即使使用CORS标头,也会污染HTML Canvas

问题描述 投票:1回答:1

我正在尝试获取图像的数据URL。该图像来自一个跨越原始的远程服务器,维基百科。我使用这个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

那么为什么这不起作用呢?我的画布还需要其他东西不被“污染”吗?

javascript image canvas cors
1个回答
4
投票

在图像上设置src时,浏览器会请求图像。但那时,你还没有设置img.crossOrigin。将img.crossOrigin线移动到img.src线上方。

这解决了受污染的画布问题,但您仍然无法获取您的URL。对图像的请求是异步的。您正尝试使用尚未加载的图像绘制到画布。将其余代码移动到图像上的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';
© www.soinside.com 2019 - 2024. All rights reserved.