applying a custom background image using CSS with local storage

Seeking to incorporate a base64 image stored in local storage under the key ImgStorage into the CSS background:

data:image/png;base64,iVBORw0KGgoAAAANS......

Experimented with two approaches:

1) Loading from storage and placing 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") + ")" });

Existing examples online mainly focus on rendering images inside an <img> tag from storage.

Has anyone successfully implemented this for a CSS background?

On a separate note, encoding images in base64 allows for embedding them within the HTML page without extra requests, potentially improving performance by reducing the number of requests. While this may not work for all browsers, it's a strategy worth considering due to the evolution of browsers over time.

Answer №1

For those who are landing on this page after searching around, I've successfully managed to make it work!

By choosing option 1), all you need to do is type the following:

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

In simple terms, there's no need to waste time trying to recreate the canvas as I initially attempted with option 2), just go straight to the point.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is causing the issue preventing me from running npm run dev on CentOS 7?

Currently facing an issue while trying to install my application on a new server after migrating from centos6 to centos7. When attempting to install a Laravel app, everything goes smoothly as it did on centos6, except for when I run npm run dev [root@v6-a ...

What is the best way to enter text into the terminal following the execution of "yarn start"?

While developing a Node chat application, I encountered an issue where I am unable to type anything in the terminal after entering "yarn start". The tutorial I am following shows that the instructor can still input commands in their terminal after running ...

What could be the reason for Internet Explorer pulling styles from the media=print CSS?

The HTML below incorporates a DHTML behavior into a CSS class. Unfortunately, Internet Explorer (specifically version 8 in compatibility mode) does not read the top style exclusively; instead, it also recognizes the @media print. <!--[if IE]> < ...

Executing background operations in Meteor.js

Let me lay out my situation: 1. Extracting data from example.com at regular intervals 2. Storing it in a Mongodb database 3. Subscribing to this data in a Meteor App. Since I'm still learning Meteor, here's my plan: 1. Develop a scraper script ...

What can I do to resolve the problem with td border

Check out my website over at browsethewebclean.com I've come across a peculiar issue with the borders and background color of some nested tables on my page. It seems that the border is not aligning properly and the background color goes beyond the im ...

Proportional fluid image grid with responsive design

After implementing various media queries, I've managed to create an image grid using Bootstrap 4+ that looks great on specific devices and layouts. Here's the reference code: .cmd-three-img-container { position: relative; margi ...

Convert a list into a hierarchical structure of nested objects

Working with angular, I aim to display a nested tree structure of folders in an HTML format like below: <div id="tree"> <ul> <li ng-repeat='folder in folderList' ng-include="'/templates/tree-renderer.html'" ...

Creating a web form with the ability to select multiple images using Javascript

Currently, I am in the process of developing an HTML form that enables users to select an image, a URL, and text that will be inserted as a <li> into a webpage. However, I am facing an issue where I want users to create multiple <li> per input. ...

Pass the value of the search input to child components in Angular 2

Within my Angular 2 application, I am faced with the task of sending the value from an HTML search input to 3 child components only when the user pauses typing for 300ms and has entered a different value than what was previously in the input field. After r ...

Is it possible for me to scrape an HTML code snippet directly from a browser?

How can I extract specific content from an HTML code block using only JS or jQuery on a browser? Below is the code I am working with: <ul> <li>New York</li> <li>London</li> <li>Madrid</li> <li&g ...

Using dynamic jquery to target specific elements. How can we apply jquery to selected elements only?

Hello everyone! I have been working on a simple hover color change effect using jQuery, but I noticed that I am repeating the code for different buttons and service icons. Is there a way to achieve the same result so that when a button is hovered, the co ...

The materialLoader in Three.js is experiencing difficulty loading an embedded texture image

When I export a material from three.js using the material.toJSON() method, I receive the following result: { "metadata":{"version":4.5,"type":"Material","generator":"Material.toJSON"}, "uuid":"8E6F9A32-1952-4E12-A099-632637DBD732", "type":"MeshStandardMat ...

Can someone show me the JavaScript code to split a string at every instance of ' '?

Hey there! I have a question about manipulating strings. Take a look at this example: var string = '"In Another World" "Magic Books"' I want to create an array that contains every name within the [""]. How can I ach ...

What is the best way to create a fading footer effect on scroll using jQuery?

Why is my footer not fading in after 1000px like I want it to? Instead, it appears immediately on the screen. I attempted using fadeIn() in jQuery but had no luck. I also tried to make it disappear with fadeOut(), again with no success. Am I missing someth ...

Combining similar validators in VueJS into one group

Upon installation of the vuelidate.js.org package for VueJs, I implemented the following validator script: }), Validations: { name: { required, minLength: minLength(3), maxLength: maxLength(50) }, family: { required, minLength: ...

Having trouble retrieving the keyword property within a Vue.js promise

Struggling with an async validation process in Vue.js where I need to globally access the $axios instance, but encountering failures Validator.extend('async_validate_job_type', { getMessage: field => `The Name already exists`, val ...

Modify/Enclose a method within a prototype

I have developed a framework that incorporates function wrapping to create a debugging tool. My current goal is to gather and report information upon the invocation of functions. Here is the initial code snippet I am working with: function wrap(label, cb) ...

Changing the color of an open Bootstrap 4 accordion panel when the page loads

I am looking to emphasize the panel that the user has opened. If a user clicks the button in the card header, the background turns red, which is working smoothly as demonstrated in the code snippet. In certain scenarios, the first panel is open by default ...

Utilizing a Bootstrap column design with two columns in place - one column set at a fixed width while the second column stretches across the remaining

Need help with adjusting two columns on a webpage? The right column is fixed at 300px width, while the left column should take up the remaining space. Using flex works well, but when adding a responsive ad to the left column, it extends beyond the availabl ...

"Utilizing the power of Angular 6's JSON pipe

Looking for a well-structured formatted JSON, but all I get is confusion and this strange image: https://i.sstatic.net/6mvBu.png Does anyone have any insights on what might be causing the issue? HTML <span style="font-weight: 500;">Payload Data: ...