Home > Software design >  Stackblitz Angular project - issue drawing image to canvas - Canvas has been tainted by CORS
Stackblitz Angular project - issue drawing image to canvas - Canvas has been tainted by CORS

Time:03-21

I am able to draw an image to the Html Canvas, and I have tried to use the 'anonymous' property, however I still cannot pull the imageData from my canvas.

The image does load, but I get the classic tainted error message.

If I add this line

  this.imageObj.crossOrigin = 'Anonymous';

the image will NOT get drawn to my canvas (and there is no error).

Please see app.component.ts, loadImage() function here:

https://stackblitz.com/edit/angular-ivy-ohaqyi?file=src/app/app.component.ts

 loadImage() {
    this.imageObj = new Image();
    // this.imageObj.crossOrigin = 'Anonymous';
    this.imageObj.src =
      'https://www.bobmazzo.com/wp-content/uploads/2009/06/bobpiano1-300x213.jpg';

    this.imageObj.onload = () => {          
      this.redraw();
    };
    
  }

*** UPDATE *** As per the answer below, the server did not open CORS. So I ended up using a more friendly image site such as https://cdn.pixabay.com/photo/2014/02/27/16/10/tree-276014_960_720.jpg

CodePudding user response:

as we can see on the errors on your stackblitz

When you add this.imageObj.crossOrigin = 'Anonymous'; you get

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.bobmazzo.com/wp-content/uploads/2009/06/bobpiano1-300x213.jpg. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200.

but when you add it, you also get an error:

ERROR DOMException: The operation is insecure.

Both errors are realted to CORS configurations.

CORS is something you need to configure on the server which provides the "https://www.bobmazzo.com" website.

for a deep dive, this is your question: Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

  • Related