Imagen con CORS habilitado

Esta traducción está incompleta. Por favor, ayuda a traducir este artículo del inglés.

La especificación HTML introduce un atributo crossorigin para imágenes que, en conjunto con el encabezado  CORS apropiado, permite definir imágenes con el elemento <img> que se carguen de orígenes externos dentro de un lienzo (canvas) como si estas fuesen cargadas del origen actual.

See CORS settings attributes for details on how the crossorigin attribute is used. Test another edit with mdn_* task queues.

What is a "tainted" canvas?

Although you can use images without CORS approval in your canvas, doing so taints the canvas. Once a canvas has been tainted, you can no longer pull data back out of the canvas. For example, you can no longer use the canvas toBlob()toDataURL(), or getImageData() methods; doing so will throw a security error.

This protects users from having private data exposed by using images to pull information from remote web sites without permission.

Example: Storing an image from a foreign origin

You must have a server hosting images with the appropriate Access-Control-Allow-Origin header.  Adding crossOrigin attribute makes a request header. You can use this excerpt from the HTML5 Boilerplate Apache server configs to appropriately respond with this response header:

<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>

Given that's all sorted, you will be able to save those images to DOM Storage as if they were served from your domain.

var img = new Image,
    canvas = document.createElement("canvas"),
    ctx = canvas.getContext("2d"),
    src = "http://example.com/image"; // insert image url here

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;
// make sure the load event fires for cached images too
if ( img.complete || img.complete === undefined ) {
    img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
    img.src = src;
}

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 13 8 Not supported Not supported ?
Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support ? ? ? ? ?

See Also

Etiquetas y colaboradores del documento

 Colaboradores en esta página: vltamara
 Última actualización por: vltamara,