Javascript: CORS enabled image

5.7k Views Asked by At

I want to be able to convert Canvas (which contains image from another domain) to Image. For this as I understood I should use CORS enabled images (to be able to use .toDataURL() for canvas). The question is how to make CORS enabled image. The following code throws an error on first line: Cross-origin image load denied by Cross-Origin Resource Sharing policy.

<html>
<body>
<input type="button" id="button" value="convert" onclick="onClick()" /></br>
<img id="output" />

<script>
    var source = "https://www.gravatar.com/avatar/7b67c827ee1671ba3b43f4aebf6794fb?s=128&d=identicon&r=PG";

    onClick = function () {
        var img = document.createElement('img');

        img.onload = function (e) {
            var canvas = document.createElement("canvas");
            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
            var url = canvas.toDataURL();
            var output = document.getElementById("output");
            output.src = url;
        };

        img.crossOrigin = 'anonymous';
        img.src = source;
    };
</script>
</body>
</html>
1

There are 1 best solutions below

4
On

Hi Suggest you check compability if you need IE I'm not sure this approach will work for you.

See here, with help on CORS enabling your images. https://developer.mozilla.org/en-US/docs/HTML/CORS_Enabled_Image

Essentially the CORS header is added to the webserver from which the image is being served, so this has to be under your control to some degree.

As I've always needed IE the simplest solution I have found is to simply setup a server side proxy to serve the images as if they come from your domain.

HTH