Crossorigin attribute for img tag

I am trying to figure out how to use the crossorigin attribute for an img tag. I could not find a good example (the ones that I found about CORS-compatible images are explained using JavaScript codes, so I could not see the crossorigin attribute with the img tag.

I have an assumption, please correct my mistakes if I understand something is wrong.

First of all, you can write the code snippet below to draw an image on the canvas:

<canvas id="canvas" width=400 height=400></canvas> <br><br> <img id="image" src="http://...." alt="" width="400" height="400"> <script> function draw() { var canvas = document.getElementById("canvas"); var context = canvas.getContext("2d"); var img = new Image(); img.crossOrigin = "Anonymous"; img.src = document.getElementById("image").value; context.drawImage(img, 40, 40); } </script> 

Is the code below equivalent to the top? It does not include "img.crossOrigin", but has the crossorigin attribute in the img tag.

 <canvas id="canvas" width=400 height=400></canvas> <br><br> <img id="image" crossorigin="anonymous"src="http://...." alt="" width="400" height="400"> <script> function draw() { var canvas = document.getElementById("canvas"); var context = canvas.getContext("2d"); var img = new Image(); img.src = document.getElementById("image").value; context.drawImage(img, 40, 40); } </script> 

Honestly, I can’t experiment, because I don’t know which site allows its images to be used as CORS.

I think that if the site allows its images to be used in the canvas, if the CORS request is executed anonymously, you can draw it in the canvas if you cannot draw it in the canvas, even if the request is anonymous (I'm not sure I'm here). Therefore, both of the above examples should request CORS anonymously.

Could you say that they both work the same? If not, could you explain why and give me an example using the crossorigin attribute with the img tag?

+7
html5 cors canvas
source share
1 answer

Since you are using the #image element as the source for your image, the 2 versions of your code are roughly equivalent.

But...

The version without crossorigin="anonymous" in the img element will probably still generate a cross-domain violation.

This is because the image was initially loaded into the img element without the cross start flag set to anonymous.

The javascript code will most likely use the cached version of the image from the img element, rather than trying to reload it from http: // ...

This means that the cached image data will still mask the canvas as containing cross-content.

BTW, syntax error in your code:

 // Not: img.src = document.getElementById("image").value; img.src = document.getElementById("image").src; 
+8
source share

All Articles