开发者

How to save a canvas drawing?

开发者 https://www.devze.com 2023-01-12 12:46 出处:网络
I have this finger-painting app and I want my users may save what they draw and come back later and keep 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 lighte开发者_JAVA技巧r way to do this?


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消