13

Currently I am using Canvas2Image to save the content of my HTML5 canvas. It doesn't appear to work in Google Chrome, however. Any ideas on how to work around the issue are welcome. :)

Kara
  • 6,115
  • 16
  • 50
  • 57
Juho Vepsäläinen
  • 26,573
  • 12
  • 79
  • 105

3 Answers3

7

canvas.toDataURL() appears to work fine in Chrome, so it may be a library issue. The "convert canvas to image" functionality seems to work, though.

Amber
  • 507,862
  • 82
  • 626
  • 550
5

use this code

<html>
<head>
<script src="base64.js" type="text/javascript"></script>
<script src="canvas2image.js" type="text/javascript"></script>
</head>
<body>
<input type="button" id="savecanvas" value="Save Image" onclick="savecanvasfile()"/>
</body>
</html>



<script>
function savecanvasfile(){
    var canvas = document.getElementById('canvas_name');
    Canvas2Image.saveAsPNG(canvas);
}
</script>

download these canvas2image.js and base64.js and save it in local folder for the working of this code.

These will be available in the site https://web.archive.org/web/20140904002425/http://www.nihilogic.dk/labs/canvas2image/

Kissaki
  • 8,810
  • 5
  • 40
  • 42
Abi
  • 65
  • 1
  • 6
  • Interesting approach but you cannot choose the file name, or am I missing something? – malber Mar 19 '13 at 08:10
  • yeah!! But I cannot choose a name while I'm running it in Chrome. But Firefox browser prompts for the file name to save it. How this can be resolved?? – Abi Mar 20 '13 at 11:28
  • In my case Firefox asks for saving the file, not for changing its name. A workaround for Chrome and IE (HTML5) without touching anything server-side is this: http://stackoverflow.com/questions/3906142/how-to-save-a-png-from-javascript-variable/15504286#15504286 . No solution yet for Firefox. – malber Mar 20 '13 at 13:09
  • Why are you assigning `context` and `strDataURI` when they are never used? – Kissaki Sep 28 '22 at 10:22
  • The linked website is dead. – Kissaki Sep 28 '22 at 10:22
  • From the archived website, looks like [`canvas2image.js`](https://web.archive.org/web/20140904024323/http://www.nihilogic.dk/labs/canvas2image/canvas2image.js) does what [canvas.toDataURL](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL) does. For the saving, it replaces the image mime type with `"image/octet-stream"` and then sets `document.location.href` to the generated data url. – Kissaki Sep 28 '22 at 10:34
4
var canvas = document.getElementById("canvas");
var strDataURI = canvas.toDataURL("image/png;base64");
document.write('<img src="'+strDataURI+'"/>');
Kissaki
  • 8,810
  • 5
  • 40
  • 42
Nitesh
  • 91
  • 4
  • Why did you include `var context = canvas.getContext("2d");`, when `context` is not being used? – Kissaki Sep 28 '22 at 10:19