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);
If you want to save just a bitmap then you can save it this way: localStorage. setItem(canvasName, canvas. toDataURL());
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With