Is there a way to set background-image as a base64

2019-01-17 13:42发布

I want to change background dynamically in JS and my set of images is in base64 encoded. I try:

document.getElementById("bg_image").style.backgroundImage = 
   "url('http://amigo.com/300107-2853.jpg')"; 

with perfect result,

yet I fail to do the same with:

document.getElementById("bg_image").style.backgroundImage = 
   "url('data:image/png;base64,iVBORw0KGgoAAAAAAAAyCAYAAAAUYybjAAAgAElE...')";

nor

document.getElementById("bg_image").style.backgroundImage = 
   "data:image/png;base64,iVBORw0KGgoAAAAAAAAyCAYAAAAUYybjAAAgAElE...";

Is there any way to do it?

8条回答
三岁会撩人
2楼-- · 2019-01-17 14:38

Adding this trick to gabriel garcia's following solution -

var img = 'data:image/png;base64, ...'; //place ur base64 encoded img here
document.body.style.backgroundImage = 'url(' + img + ')';

However, in my case this wasn't working. Moving url into the img variable did the trick. SO the final code looked like this

var img = "url('data:image/png;base64, "+base64Data + "')";
document.body.style.backgroundImage = img; 
查看更多
\"骚年 ilove
3楼-- · 2019-01-17 14:45

I tried this (and worked for me):

var img = 'data:image/png;base64, ...'; //place ur base64 encoded img here
document.body.style.backgroundImage = 'url(\'' + img + '\')';

ES6 syntax:

let img = 'data:image/png;base64, ...'
document.body.style.backgroundImage = ´url('${img}')´

A bit better:

let setBackground = src=>{
    this.style.backgroundImage = `url('${src}')`
}

let node = nodeIGotFromDOM, img = imageBase64EncodedFromMyGF
setBackground.call(node, img)
查看更多
登录 后发表回答