0

I've tried doing this for a few hours, and I've tried every solution that I could find both on stackoverflow and on other sites, without success.

The most remarkable thing is that every solution is completely or at least distinctly different from one another. And wc3schools and sites like that seem to have no default way of solving this whatsoever.

I have this simple HTML-document with this body:

<body onload="draw();">

<canvas id="canvas1" width="500" height="500"></canvas>

</body>

And this js-document:

// JavaScript Document

function draw() {

    var canvas1 = document.getElementById('canvas1');

    if(canvas1.getContext) {
        var ctx = canvas1.getContext('2d');

        //Here's a lot of drawing that I've removed to make everything that's relevant more readable.

    }
}

So this is what I'm working with, and as u can see I've removed all of the code drawing on the canvas since that code shouldn't be necessary to know to save the canvas (please tell me if it is, though).

I don't really care what format I'm saving in or how I do it (by clicking on a button I have to implement/by right-clicking on the canvas/other solutions), I just want to know how to do it in the simplest possible way!

Charles
  • 50,943
  • 13
  • 104
  • 142
Jonatan Stenbacka
  • 1,824
  • 2
  • 23
  • 48
  • 1
    "Simple" means different things to different people. But displaying `canvas.toDataURL` on a new browser tab and having users right-click-to-save is simple and works in most browsers. Solutions that try to get "simpler" than that by trying to avoid user verification will likely run afoul of browser security. – markE Mar 24 '14 at 16:16
  • 1
    possible duplicate of [How To Save Canvas As An Image With canvas.toDataURL()?](http://stackoverflow.com/questions/10673122/how-to-save-canvas-as-an-image-with-canvas-todataurl) – Charles May 19 '14 at 18:47

1 Answers1

0

I managed to accomplish this in quite a simple way after all. This simple code was all that was needed to enable the user to right-click on the canvas and saving it, as you would with any other picture. Not only is it simple to implement, but I also think that it's the most desirable solution since it's the way we usually save pictures on the internet.

var saveImage = canvas1.toDataURL("image/png").replace("image.png", "saveImage/octet-stream");
window.location.href = saveImage;

"canvas1" is the name of the canvas I want to save, and "image/png" has nothing to do with my code but is some default name that we replace with "saveImage/octet-stream", which is my canvas in this case.

I can't really explain in detail what this code does, but it works!

Jonatan Stenbacka
  • 1,824
  • 2
  • 23
  • 48