我有兴趣在我的网站上使用smartcrop.js和一些用户上传的图片。用户可以将任何大小的图像上传到我的Amazon S3存储桶。然后,该图像与用户相关联,当他们访问他们的个人资料时,他们可以看到图像很好地裁剪。当我尝试在图像元素上使用smartcrop执行某种操作时,我得到错误:
smartcrop.js:282 Uncaught DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.
可以通过以下步骤复制:
var image = new Image();
image.src = "https://freelancestudent.s3.amazonaws.com/files/google.png"
SmartCrop.crop(image, {width: 100, height: 100}, function(result){console.log(result);});
smartcrop.js:282 Uncaught DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.
我已经在S3控制面板中检查了CORS配置编辑器,它看起来像这样:
<CORSConfiguration>
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
</CORSConfiguration>
我的理解是<AllowedOrigin>*</AllowedOrigin>
应该意味着这个问题不应该存在?我已经阅读了一个解决方案,我可以将图像保存到服务器上进行显示,但我希望保持静态文件和生产服务器分开。有什么想法吗?
答案 0 :(得分:7)
我能够通过略微修改我的CORS规则来实现这一目标:
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
在图片上将 crossOrigin 设置为anonymous
:
image.crossOrigin = 'anonymous';
完整的命令集:
var image = new Image();
image.crossOrigin = 'anonymous';
image.src = "https://s3-us-west-2.amazonaws.com/boom-orca/people-deal-header.png";
SmartCrop.crop(image, {width: 100, height: 100}, function(result){console.log(result);});
截图: