Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hml5 toDataUrl() not working on chrome

I do this:

$('#displayBtn').click(function(){
    var canvas = document.getElementById("myCanvas");
    var dataUrl = canvas.toDataURL();
    document.getElementById("textArea").value = dataUrl;
});

It works great on Firefox and IE, but no luck with Chrome. I googled and came back with the issue relating to .SVG files, but I'm not using any SVG files, only PNG and JPG. Here is a fiddle of my code: http://jsfiddle.net/ykpCn/2/ Is it because I'm using transparent PNGs? Not sure what I'm doing wrong. Very new to HTML5, I hope it's not something stupid that I've overlooked.

like image 626
Silas Avatar asked Oct 27 '25 08:10

Silas


2 Answers

The issue is related to Cross origin resource access. The image you have rendered on the canvas is from a different origin (http://moosepi.com). You can't call toDataURL() on images which are from different origins.

If you fire up your Chrome developer tools, you will find this in your console. "Uncaught Error: SECURITY_ERR: DOM Exception 18". This is the expected behavior as per the spec.

Solution: 1. Host the images from your server (may be using a Proxy setup). 2. Set CORS attribute on the resource. Remember the source must set the appropriate headers.

like image 52
Varunkumar Nagarajan Avatar answered Oct 28 '25 21:10

Varunkumar Nagarajan


Apparently that ONLY works on Chrome if it's being hosted on a webserver? It works fine if I upload to the server and then view it from there, but will not work locally. My question is stupid now. Sorry for wasting time.

like image 27
Silas Avatar answered Oct 28 '25 23:10

Silas