Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a canvas drawing?

I have this finger-painting app and I want my users may save what they draw and come back later and keep drawing.

What's the lighter way to do this?

like image 241
Erik Escobedo Avatar asked Aug 19 '10 16:08

Erik Escobedo


3 Answers

One way you could do this is:

Save the canvas contents as a base64 encoded PNG image by calling canvas.toDataURL() and store the encoded string in the page's localStorage.

When you want to restore the canvas, you would create an image, set the src to be the value previously stored locally and then draw that image on the canvas.

There are other methods, such as recording all the drawing operations, storing them locally or in a server session and 'replaying' them when the page is next visited.

like image 155
andrewmu Avatar answered Nov 08 '22 14:11

andrewmu


HTML Save button:

  <input type="button" id="save" value="Save to PNG"> 

Then script:

  document.getElementById('save').onclick = function () {
    window.location = document.getElementById("canvas").toDataURL('image/png');
  };

Then you'll have to use Canvases's drawImage with the image that was saved. How/where you save the image (your server, their downloads folder) depends on how you want it loaded back.

like image 33
Simon Sarris Avatar answered Nov 08 '22 14:11

Simon Sarris


you can use fabric js. It has method which help serialize to JSON and then you can save this JSON in DB. documentation

like image 1
Владимир Ефанов Avatar answered Nov 08 '22 14:11

Владимир Ефанов