setting css background to an image in local storag

2019-04-09 13:53发布

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.

1条回答
女痞
2楼-- · 2019-04-09 14:45

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:

var TheImage = localStorage.getItem('ImgStorage');
$('body').css({ 'background-image': "url(" + TheImage + ")" });

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.

查看更多
登录 后发表回答