EaselJs - 跨域图像解决方法?

EaselJs - cross-domain images workaround?

当我尝试使用时:

temp = new createjs.Bitmap(obj.path)

我收到错误:

Uncaught An error has occurred. This is most likely due to security restrictions on reading canvas pixel data with local or cross-domain images.

这和this question有点关系。除了上述情况,用户没有使用网络服务器。

在我的例子中,我使用的是网络服务器,但我需要使用 https 将图像托管在 AWS S3 存储桶上。

有没有我可以用来允许 CORS 与 EaselJs 的设置?

S3 存储桶上的 CORS 设置:

<CORSConfiguration>
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>Authorization</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

编辑:

是的,在权限下的 AWS S3 存储桶上启用 CORS。

Bitmap 不处理 CORS,因为您必须在 设置 src 之前 直接在图像上定义跨源 属性。

执行此操作的最佳方法是自己创建图像,然后在将其传递给位图之前应用跨源。

var image = document.createElement("img");
image.crossOrigin = "Anonymous"; // Should work fine
image.src = obj.path;
temp = new Bitmap(image);

目前EaselJS上没有API可以通过crossOrigin,所以这是唯一的方法。

如果您使用 PreloadJS 预加载 EaselJS 内容,您可以在队列或任何加载项目上传递 crossOrigin 属性。

var queue = new createjs.LoadQueue(false, null, true); //3rd param
queue.loadFile("path/to/bmp.png"); // Will use the queue CORS
queue.loadFile({src:"path/to/bmp.png", crossOrigin:true, id:"image"}); // For one file only (you can leave out the param on LoadQueue)
// later
var bmp = new createjs.Bitmap(queue.getResult("image");

请注意,即使图像显示,您仍会收到 CORS 错误的原因是 EaselJS 使用像素填充来确定命中测试。您还可以通过将 hitAreas 放在图像上来解决这个问题,在进行命中测试时使用 hitAreas 代替图像像素:

var temp = new Bitmap(obj.path);
temp.image.onload = function() {
    var s = temp.hitArea = new createjs.Shape();
    s.graphics.fill("red").drawRect(0,0,temp.image.width,temp.image.height);
}

干杯,