Convert canvas to an image with JavaScript

49,540

You have the right idea, and it will work in very simple cases such as:

var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');

ctx.fillRect(50,50,50,50);

var img = new Image();
img.src = can.toDataURL();
document.body.appendChild(img);

http://jsfiddle.net/simonsarris/vgmFN/

But it becomes problematic if you have "dirtied" your canvas. This is done by drawing images to the canvas that are from a different origin. For instance, if your canvas is hosted at www.example.com, and you use images from www.wikipedia.org, then your canvas' origin-clean flag is set to false internally.

Once the origin-clean flag is set to false, you are no longer allowed to call toDataURL or getImageData


Technically, images are of the same origin if domains, protocols, and ports match.


If you are working locally (file://) then any image drawn will set off the flag. This makes debugging annoying, but with Chrome you can start it with the flag --allow-file-access-from-files to allow this.

Share:
49,540
mmpatel009
Author by

mmpatel009

Updated on October 05, 2021

Comments

  • mmpatel009
    mmpatel009 over 2 years

    I want to convert canvas to an image with JavaScript, When I try to canvas.toDataURL("image/png"); It gives the following error

    SecurityError: The operation is insecure

  • Adrian
    Adrian almost 11 years
    +1 for the Chrome flag, I hadn't heard about that but absolutely useful in many cases. Thanks!!
  • apsillers
    apsillers over 10 years
    This answer is not relevant to the question, which does not use jqPlot and asks about an error when trying to stringify image data. Your example does solve the problem because it does not have the conditions necessary to reproduce the issue (namely, cross-domain image resources).
  • shruti
    shruti almost 4 years
    Thanks...!! Simon, Very simple and descriptive answer :)