Search code examples
javascriptamazon-s3fabricjsamazon-cloudfront

Cross origin on fabric.Image.fromURL breaks CORS even with crossOrigin set


Using fabric.js I'm attempting to load a background image from an amazon cloudfront/s3 url.

fabric.Image.fromURL(imgURL, function(img) {
    canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas),
    {
        scaleX: canvas.width / img.width,
        scaleY: canvas.height / img.height
    });
}, {crossOrigin: 'anonymous'});

When crossOrigin is present, I get the standard error

Access to image at '...' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

When I remove the crossOrigin anon. It will load the image, however it taints the canvas so that I cannot use toDataURL.

CORS Headers


Solution

  • When I remove the crossOrigin anon. It will load the image, however it taints the canvas so that I cannot use toDataURL.

    This is the default position. If you don't specify it, then it won't allow you to do anything that requires CORS permission.

    When crossOrigin is present, I get the standard error

    Access to image at '...' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

    anonymous means "Check for CORS permission, but don't send user credentials to a different origin".

    So instead of just forbidding access to features that need CORS permission, it first checks for CORS permission, discovers that you don't have it, then forbids access.

    You need the server you are requesting the image from to provide your JavaScript with permission to read the data using CORS.