FabricJS ReactJS CORS 错误

Posted

技术标签:

【中文标题】FabricJS ReactJS CORS 错误【英文标题】:FabricJS ReactJS CORS Errors 【发布时间】:2018-06-26 02:43:00 【问题描述】:

我有一个使用 ReactJS 构建的应用程序,我在其中广泛使用 FabricJS。对于 FabricJS,我使用的是 https://www.npmjs.com/package/fabric-webpack。图像托管在 S3 存储桶上。存储桶的 CORS 配置:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <ExposeHeader>ETag</ExposeHeader>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

问题是画布被一些图像污染并引发错误:

fabric.js:11485 Uncaught DOMException: Failed to execute 'toDataURL'
on 'htmlCanvasElement': Tainted canvases may not be exported.
    at n.__toDataURL (main.eab7fbf7.js:14:4552)
    at n.__toDataURLWithMultiplier (main.eab7fbf7.js:14:4342)
    at n.toDataURL (main.eab7fbf7.js:14:3894)
    at f (main.eab7fbf7.js:9:22786)
    at HTMLDivElement.<anonymous> (main.eab7fbf7.js:9:27492)
    at HTMLDivElement.dispatch (main.eab7fbf7.js:5:20443)
    at HTMLDivElement.g.handle (main.eab7fbf7.js:5:18462)
__toDataURL @ fabric.js:11485
__toDataURLWithMultiplier @ fabric.js:11464
toDataURL @ fabric.js:11434
f @ board.js:713
(anonymous) @ board.js:396
dispatch @ jquery.js:5201
g.handle @ jquery.js:5009

我有什么遗漏吗?

【问题讨论】:

如果您处于开发模式,请从 appstore 在 chrome 中安装 CORS 扩展。 您是否使用 crossOrigin 选项在 fabricjs 中加载图像?你能展示你如何从 s3 存储桶加载图像吗? 【参考方案1】:

您只需要在您的图像对象中添加“crossOrigin”,然后您的意志就会消失。如果不添加它,它总是会出现这种错误。

元素['crossOrigin'] = "匿名"

【讨论】:

【参考方案2】:
image = 'http://asd.com/myImg.jpg' 
fabric.Image.fromURL(
          image,
          function(img) 
            canvas.add(img)
            canvas.renderAll()
          ,
          crossOrigin: "anonymous",
        )

【讨论】:

以上是关于FabricJS ReactJS CORS 错误的主要内容,如果未能解决你的问题,请参考以下文章

在 ReactJS 中获取 onComponentDidMount 期间出现 CORS 错误

我已经设置了标题然后还有 CORS 策略错误(ReactJS)

来自 Django 服务器的 reactjs 请求时出错(403 错误/CORS)

CORS 错误 - 错误:禁止跨源 http://localhost - 仅在 ReactJS/Jest 测试中

NodeJS Express和ReactJS的CORS错误[重复]

尝试执行 localhost API 时在 ReactJS 应用程序中出现 CORS 错误