The HTML specification document introduces the crossorigin attribute for images. By setting the appropriate header information CORS, img images can be loaded from other sites and used in canvas, just like downloaded directly from the current site (current origin).
For details on the use of crossorigin attributes, please refer to CORS settings attributes.
What is a tainted canvas?Although it is possible to use images in canvas without CORS authorization, doing so will taint the canvas. As long as the canvas is contaminated, data can no longer be extracted from the canvas, which means that methods such as toBlob(), toDataURL() and getImageData() cannot be called, otherwise a security error will be thrown.
This is actually to protect users' personal information and avoid loading users' image information from remote web sites without permission, causing privacy leaks.
Example: Saving pictures from other sites(Translator's note: If the user has logged into social networking sites such as QQ, if no protection is provided, the website may use canvas to obtain and upload the user's image information after opening a website, thereby causing leakage.)
First, the image server must set the corresponding Access-Control-Allow-Origin response header. Add the crossOrigin attribute of the img element to the request header. For example, the Apache server can copy the configuration information in the HTML5 Boilerplate Apache server configs to respond:
<IfModule mod_setenvif.c> <IfModule mod_headers.c> <FilesMatch /.(cur|gif|ico|jpe?g|png|svgz?|webp)$> SetEnvIf Origin : IS_CORS Header set Access-Control-Allow-Origin * env=IS_CORS </FilesMatch> </IfModule></IfModule>
After these settings take effect, you can save images from other sites to DOM storage (or other places) just like the resources of this site.
var img = new Image, canvas = document.createElement(canvas), ctx = canvas.getContext(2d), src = http://example.com/image; // Specific image address img.crossOrigin = Anonymous;img. onload = function() { canvas.width = img.width; canvas.height = img.height; ctx.drawImage( img, 0, 0 ); localStorage.setItem( savedImageData, canvas.toDataURL(image/png) );}img.src = src;// Ensure that the cached image also triggers the load event if ( img.complete || img.complete === undefined ) { img.src = data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==; img.src = src;}Browser compatibility
Desktop
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | 13 | 8 | Nosupport | Nosupport | ? |
Mobile
| Feature | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|
| Basic support | ? | ? | ? | ? | ? |
See also
Chrome: Using cross-origin images in WebGL
HTML specification-crossorigin attribute
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.