I'm looking to put an image that's in base64 format and that's stored in the local storage in the key ImgStorage
like this in the css background:
data:image/png;base64,iVBORw0KGgoAAAANS......
So far, I've tried two approaches:
1) loading from storage and put in css tag:
var TheImage = localStorage.getItem('ImgStorage');
$('body').css({ 'background-image': "url(" + TheImage) });
2) recreating the canvas from the storage data:
var Canvas = document.createElement("canvas");
Canvas.width = 50;
Canvas.height = 50;
var Context = Canvas.getContext("2d");
var TheImage = localStorage.getItem('ImgStorage');
Context.drawImage(TheImage, 0, 0);
Canvas.toDataURL("image/png");
$('body').css({ 'background-image': "url(" + Canvas.toDataURL("image/png") + ")" });
I've looked around on the web but all examples talk about getting an image in storage to render inside an <img>
tag.
Has anyone solved this for css background?
As an aside, in terms of performance, if you base64 encode your images, you can send them in the body of the HTML page without any additional requests. So for example, if you need to load 20 images for your UI, that's 20 less requests. And, if you store each image in the local storage, then you only need to load them once. Doesn't work for older browsers so it only works for 80% of browsers but still.... something to consider because time's on your side in terms of browser evolution.
ok, this is for those who come to this page after bouncing around: I GOT IT TO WORK!!!!
Using option 1), you simply write this:
In other words, you don't need to waste your time reccreating the canvas like I was trying to with option 2), just go direct.