1

I want to get the 64 base encode of the canvas. Below code throw an security exception: Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

<canvas id="canvas" width="345" height="345"></canvas>

var 
    canvas = document.getElementById("canvas"),
    ctx = null,
    img    = new Image(),
    dataUrl = null;

var init = function() {
    img.onload = function () {
        ctx.drawImage(img, 0, 0);
        dataUrl = canvas.toDataURL();
    };
    /*img.crossOrigin = "Anonymous";*/
    img.src = "./img/s1.jpg";
    console.log(dataUrl);   
};

if (Modernizr.canvas) {
    ctx = canvas.getContext("2d");
    init();
}

I also tried to add img.crossOrigin = "Anonymous"; but then i get this exception Image from origin 'file://' has been blocked from loading by Cross-Origin Resource Sharing policy: Invalid response. Origin 'null' is therefore not allowed access.

Moiz Farooq
  • 1,018
  • 9
  • 11
  • `The toDataURL method will fail if the browser thinks you've drawn to the canvas any data that was loaded from a different origin, so this approach will only work if your image files are loaded from the same server as the HTML page whose script is performing this operation.` from http://stackoverflow.com/questions/15685698/getting-binary-base64-data-from-html5-canvas-readasbinarystring – IrkenInvader Apr 13 '16 at 21:15
  • Ok. Now run it to `localhost` not getting any exception but the `dataUrl ` value to null. – Moiz Farooq Apr 13 '16 at 21:26
  • and what about the `img.crossOrigin = "Anonymous";`? Did you re-added it to the code? – Alon Eitan Apr 13 '16 at 22:01

0 Answers0