Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving and loading canvas data from localStorage

I need to save all drawings from my canvas in order to be able to return to them later on.

I succeed in getting and putting data but I can't save the object and return it correctly.

This is my code:

var imgData = a.getImageData(0, 0, 500, 200);
localStorage.setItem("test",JSON.stringify(imgData))
console.log(imgData)
console.log(JSON.parse(localStorage.getItem("test")))
b.putImageData(imgData, 0, 0);
like image 840
Albaz Avatar asked Sep 26 '22 18:09

Albaz


People also ask

How do I save my canvas on local storage?

If you want to save just a bitmap then you can save it this way: localStorage. setItem(canvasName, canvas. toDataURL());

Can localStorage be hacked?

On the downside, localStorage is potentially vulnerable to cross-site scripting (XSS) attacks. If an attacker can inject malicious JavaScript into a webpage, they can steal an access token in localStorage. Also, unlike cookies, localStorage doesn't provide secure attributes that you can set to block attacks.

Can JSON values be added in localStorage?

Storing JSON, Functions And Arrays in localStorage Luckily, we can store complex data in localStorage by leveraging the JSON object's stringify() and parse() functions. JSON support is quite good on mobile but if you need to add support use json2.


1 Answers

You can use the canvas.toDataURL() method which will encode the canvas into Base64.

You can then create a image with the source being the data url and then draw that image to the canvas.

Here is the working sample.

var canvas = document.getElementById('tutorial');
var ctx = canvas.getContext('2d');

var ctx = canvas.getContext("2d");

ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (10, 10, 55, 50);

var url = canvas.toDataURL();

localStorage.setItem('url', url);

var canvas2 = document.getElementById('tutorial2');
var ctx2 = canvas2.getContext("2d");
var toDrawUrl = localStorage.getItem('url');

drawDataURIOnCanvas(toDrawUrl, ctx2);
ctx2.fillStyle = "rgb(200,200,0)";
ctx2.fillRect (20, 20, 55, 50);


function drawDataURIOnCanvas(strDataURI, context) {
    "use strict";
    var img = new window.Image();
    img.addEventListener("load", function () {
        context.drawImage(img, 0, 0);
    });
    img.setAttribute("src", strDataURI);
}
like image 178
blessanm86 Avatar answered Nov 03 '22 20:11

blessanm86