manhthe
manhthe

Reputation: 41

Fabricjs Failed to execute 'texImage2D' on 'WebGLRenderingContext': The image element contains cross-origin data, and may not be loaded

I'm using Amazon S3 and cloud front. The image url look like https://t.pimg.jp/061/089/535/2/61089535.jpg

My code look like

const imgUrl = 'https://t.pimg.jp/061/089/535/2/61089535.jpg';
fabric.util.loadImage(imgUrl, function(imgObj) {
    const oImg = new fabric.Image(imgObj, {
        crossOrigin: 'anonymous',
    });

    ...
});

The image loaded successfully. But when I apply filter to that image, the error appears.

Already applied the cors config at s3 bucket

<CORSConfiguration>
 <CORSRule>
   <AllowedOrigin>*</AllowedOrigin>
   <AllowedMethod>GET</AllowedMethod>
   <AllowedHeader>*</AllowedHeader>
 </CORSRule>
</CORSConfiguration>

Do anyone know how to fix?

Upvotes: 4

Views: 12345

Answers (1)

shkaper
shkaper

Reputation: 4998

  1. If you want to use util.loadImage(), you should supply it the crossOrigin parameter. In your code you're setting the crossOrigin: 'anonymous' in the callback - the image is already downloaded with the wrong CORS policy by that time.
  2. The image in your question doesn't actually have access-control-allow-origin header set, at least not at the time of my writing. So I've used a different image as an example:

const canvas = new fabric.Canvas('c')
const imgUrl = 'https://c1.staticflickr.com/9/8873/18598400202_3af67ef38f_q.jpg'

fabric.util.loadImage(imgUrl, (imgObj) => {
    const img = new fabric.Image(imgObj)
    img.filters.push(new fabric.Image.filters.Grayscale())
    img.applyFilters()
    canvas.add(img)
}, null, 'anonymous')
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.js"></script>
<canvas id="c" width="300" height="200"></canvas>

I'd also suggest using fabric.Image.fromURL() - it's a cleaner way to load an image:

fabric.Image.fromURL(imgUrl, (img) => {
    img.filters.push(new fabric.Image.filters.Grayscale())
    img.applyFilters()
    canvas.add(img)
}, {crossOrigin: 'anonymous'})

Upvotes: 7

Related Questions