user1145874
user1145874

Reputation: 969

saving canvas for future use

I'm relatively new to the HTML5/JS area. So maybe it's quite simple what I want to do.

I have the following requirement from a users perspective:

The user does some drawing on a canvas and then leaves the page. Once he returns, the previeous drawing should be restored and the user can proceed drawing.

What I have so far:

So what I need is to find a way to send the current drawing to the backend, store it there and reload and redraw it once the page is accessed again. How to send the data to the backend and how to retrieve it is clear to me. So the main questions are:

Thanks!

Upvotes: 0

Views: 105

Answers (2)

Philipp
Philipp

Reputation: 69663

When you don't want to use a backend server, client-sided storage is an option.

Use context.getImageData to get a structure which is a binary representation of the image content and then store it in localstorage with localstorage.setItem("savedImage", imagedata).

When your website is loaded, load the imagedata from localstorage with var imagedata = localstorage.getItem("savedImage") and place it on the canvas with putImageData. When the user visits the website for the first time or their localstorage got cleared in the meantime, imagedata will be null.

Upvotes: 1

RanSch
RanSch

Reputation: 469

I think you should set an interval that makes ajax calls (every 5 seconds, for example) and sends the drawing, so even if the connection with the server was gone there is a backup to the drawing. Or, better, you can save the drawing with localStorage. I would use localStorage, I think it's better.

In order to get the drawing, you can use getImageData function. You can read about it here : http://www.w3schools.com/tags/canvas_getimagedata.asp.

In order to redraw, when the user enters the page you can use putImageData function. You can read about it here : http://www.w3schools.com/tags/canvas_putImageData.asp.

Another solution is to use toDataURL - about this technique you can read here : http://www.html5canvastutorials.com/advanced/html5-canvas-get-image-data-url/ http://www.html5canvastutorials.com/advanced/html5-canvas-load-image-data-url/

Upvotes: 0

Related Questions