Open In App

How to allow cross-origin use of images and canvas ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to allow the use of the cross-origin for images and canvas, i.e., utilizing the images and canvas from the foreign website. To accomplish this task, the images can be utilized from other websites to our HTML document, simply by implementing the <img> tag and assign the URL to the src attribute. Although, most probably most of the time, we may get a CORS(Cross-Origin Resource Sharing) error. This is done for security purpose, due to which we are not able to use that images directly and may need to send a request with or without credentials like cookies. For this, the crossorigin attribute will be used that describes the handling of the cross-origin requests by the element, thereby enables the CORS requests configuration for the element’s fetched data. In other words, the crossorigin attribute sets the mode of credentials while making an HTTP CORS request but it works only with website hosting serving having the Access-Control-Allow-Origin HTTP header.

Syntax: Use the below syntax for using the crossorigin attribute:

<img src="https://the_image_URL" cross-origin="use-credentials">

Attribute values: Possible value of cross-origin attribute are “” , “anonymous” or “use-credentials”, that are described below:

  • use-credentials: A request is made that uses CORS headers which is set to include for the element to the foreign site by supplying user credentials such as cookies, SSL certificates, or HTTP authentication.
  • anonymous: A request is made that uses the CORS headers, along with setting the value for credentials flag as same-origin. Here is no exchanges are done for user credentials using the cookies, SSL certificates, or HTTP authentication, unless destination is the same origin.
  • “” : A request is made by setting an empty value to the attribute name, i.e., the request made for the element to the foreign site without supplying any user credentials.

Using canvas to display crossorigin images: Now, there are many situations in which we may want to use the image as a canvas(maybe to animate the image), but to be able to use it, we have to use the crossorigin property in Javascript. 

Canvas Security: A canvas can be used to display images and videos from various sources but it may cause a security problem if the source does not allow crossOrigin. If we draw in a canvas with data from any foreign source without CORS approval the canvas becomes tainted. A canvas is referred to as tainted when it is no longer secure. In a tainted canvas, there is no way to get the retrieved data as it will cause an exception.

There are some restrictions for the canvas elements that are described below:

  • The canvas isn’t allowed to retrieve <img> or <svg> HTML elements from a foreign source.
  • If the canvas is used to obtain an image as HTMLCanvasElement or ImageBitMap and the image does not satisfy the same origin rules then reading the canvas data is blocked.

If a canvas is tainted then the getImageData(), toBlob() & toDataURL() function call will result in a Security Error. The Security error prevents private data to be exposed by images taken from foreign websites without permission.

Display or Store images from the foreign origin: The first step is to have a web server which has the Access-Control-Allow-Origin HTTP header configured. This header permits cross-origin access to image files.

Prerequisite configuration to be done on the webserver: Adding the below code to an Apache server will allow graphic files of this server to be accessed by any site on the internet.

<IfModule mod_setenvif.c>
  <IfModule mod_headers.c>
    <FilesMatch "\.(avifs?|bmp|cur|gif|ico|jpe?g|jxl|a?png|svgz?|webp)$">
      SetEnvIf Origin ":" IS_CORS
      Header set Access-Control-Allow-Origin "*" env=IS_CORS
    </FilesMatch>
  </IfModule>
</IfModule>

Note: For the various server, the process of adding the HTTP header is different from the above code for the Apache server.

Display the image on the site: The server from which you want to display an image must have the above prerequisite.

Example 1: The below example illustrates displaying an image from a foreign site using canvas using the crossOrigin property.  

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>
        Allowing cross-origin use of images and canvas
    </title>
</head>
 
<body>
    <canvas id="Canvas"></canvas>
 
    <script>
     
        // Any foreign website URl
        var imageUrl =
 
        // Creating canvas element
        var canvas = document.getElementById('Canvas');
 
        // Creating new Image object with the name img
        var img = new Image();
 
        // Setting cross origin value to anonymous
        img.crossOrigin = 'anonymous'
 
        // The Image URL is been set to the
        // src property of the image
        img.src = imageUrl
 
        // This function waits until the image being loaded.
        img.onload = function () {
 
            // Matches the canvas width to that of the image
            canvas.width = this.width
 
            // Matches the canvas height to that of the image
            canvas.height = this.height
 
            // Displays the image to the canvas tag of id Canvas
            canvas.getContext('2d').drawImage(this, 0, 0)
        }
    </script>
</body>
 
</html>


Note: As the crossorigin is not supported by the GFG server that allows to access, so, we may not get the output if we use the image URL that is used in the code.

Output:

The Geeks for Geeks logo 

Add the Download button for the image: The server from which you want to display an image must have the above prerequisite.

Example 2: The below example describes the allowing the users to download the foreign image using a download button. We then converted the image to DataUrl and use the <a> tag to trigger the download.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0" />
 
    <title>
        Allowing cross-origin use of images and canvas
    </title>
</head>
 
<body>
    <div id="display"></div>
 
    <button onclick="Download()">
        DOWNLOAD
    </button>
     
    <script>
        function Download() {
 
            // Hard coded image URL change the URL according
            // to the image you want to download
            let imgURL =
 
            let foreignImg = new Image();
 
            // Set the cross origin to "anonymous" or
            // "use-credentials" according to the
            // server needs
            foreignImg.crossOrigin = "anonymous";
            foreignImg.src = imgURL;
 
            // The imageLoad function is called after proper
            // loading of the image
            foreignImg.addEventListener("load", imageLoad);
 
            function imageLoad() {
 
                // This function is called display and start
                // the download of the image
                const display = document.getElementById("display");
                let canvas = document.createElement("canvas");
                let context = canvas.getContext("2d");
                canvas.width = foreignImg.width;
                canvas.height = foreignImg.height;
                context.drawImage(foreignImg, 0, 0);
                display.appendChild(canvas);
                var image = canvas.toDataURL();
                var tempLink = document.createElement("a");
                tempLink.download = "image.png";
                tempLink.href = image;
                document.body.appendChild(tempLink);
                tempLink.click();
                document.body.removeChild(tempLink);
            }
        }
    </script>
</body>
 
</html>


Note: As the crossorigin is not supported by the GFG server that allows to access, so, we may not get the output if we use the image URL that is used in the code.

Output:

Downloading image



Last Updated : 31 Aug, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads