Skip to content
Advertisement

HTML5 – passing Canvas between files

I have two html files, say 1.html and 2.html with 1.js and 2.js referenced javascripts. In 1.html I have a Canvas object with drag and drop functionality, so that i use drawImage method for adding additional images to the canvas. When I am finished with adding images on 1.html, i save the canvas to the localStorage. Shortly it would be like:

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

ctx.drawImage(imageObj, x, y, imageObj.width, imageObj.height);
ctx.drawImage(imageObj2, x2, y2, imageObj2.width, imageObj2.height);

localStorage.setItem("context1", ctx);  // Unsure if i should save context or canvas

Now, in 2.html, i want to retrieve saved in 1.html canvas and set/apply it on the 1.html, so here i do like:

var savedContext = localStorage.getItem("context1");

var canvas1 = document.getElementById('canvas1');
var context1 = savedContext;

And I am not getting any results, I don’t even know if it is possible at all to pass Canvas like that with all the images that were drawn on it, or maybe there is another way to do so

Advertisement

Answer

You might be able to do what you are wanting by saving a data url rather than trying to save the canvas or context:

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

ctx.drawImage(imageObj, x, y, imageObj.width, imageObj.height);
ctx.drawImage(imageObj2, x2, y2, imageObj2.width, imageObj2.height);

localStorage.setItem("imageData", canvas.toDataUrl());

And restore it later:

var img = document.createElement('img');
img.src = localStorage.getItem("imageData");

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

ctx.drawImage(img, x, y, img.width, img.height);

You may also have to wait for the “onload” event to fire on the img before you can draw it on the canvas, but I’m not sure.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement