简体   繁体   English

从localStorage base64字符串设置背景图像

[英]set background-image from localStorage base64 string

I have a function that encodes an image into base64 string and stores it into localStorage. 我有一个将图像编码为base64字符串并将其存储到localStorage的函数。 I am trying to retrieve the image from localStorage and use it to set a background-image with jQuery. 我正在尝试从localStorage检索图像,并使用它通过jQuery设置背景图像。

Everything is working right, but the image isn't displaying. 一切正常,但未显示图像。 When I inspect the element in the browser, the single quotes around the 'data' uri aren't being inserted. 当我在浏览器中检查元素时,不会插入“数据” uri周围的单引号。 I don't know if this is the problem or not. 我不知道这是否是问题。

Here is my code 这是我的代码

function to encode and store image: 编码和存储图像的功能:

var img = document.getElementById("elephant");

function getBase64Image(img) {
    // Create an empty canvas element
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    // Get the data-URL formatted image
    // Firefox supports PNG and JPEG. You could check img.src to
    // guess the original format, but be aware the using "image/jpg"
    // will re-encode the image.
    var dataURL = canvas.toDataURL("image/png");
console.log(dataURL);

    return dataURL;     
}

jQuery to set the image: jQuery设置图像:

localStorage.setItem("background" , getBase64Image(img));
console.log(localStorage);

background = localStorage.getItem("background")

console.log(background);

$("#elephant2").css('background-image' , 'url(' +background+ ')');

I thought the issue was missing quotes, but it was actually corrupted/incomplete base64 data string. 我以为该问题缺少引号,但实际上它已损坏/不完整的base64数据字符串。 I placed the function inside window.onload = function () so the image loaded entirely before converting to a string and it works like a charm/ 我将函数放置在window.onload = function()中,因此图像在转换为字符串之前已完全加载,它的工作方式类似于charm /

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM