Javascript: Convert Canvas to Image in Chrome

2.8k views Asked by At

I have following code that works fine in IE but not in Chrome (Version 31.0.1650.63 m).
Error message: Failed to execute 'toDataURL' on 'HTMLCanvasElement': tainted canvases may not be exported.

<html>
<body>
<img id="source" src="C:\test.jpg" /></br>
<input type="button" value="convert" onclick="onClick()" /></br>
<img id="output" />

<script>
    onClick = function () {
        var source = document.getElementById("source");
        var canvas = document.createElement("canvas");
        canvas.width = source.width;
        canvas.height = source.width;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(source, 0, 0);
        var output = document.getElementById("output");
        output.src = canvas.toDataURL("image/png");
    };
</script>

</body>
</html>

I saw a lot of similar questions here but didn't find the answer. Any help would be appreciated.

1

There are 1 answers

0
Gideon On BEST ANSWER

From MDN:

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.

So the image you are drawing on your canvas comes from another domain, and so you are not allowed to use the canvas to export the data. See the MDN article for more info.