Let's assume there is a DIV element and it has CSS background-image property.
I want to get urldata(base64) of the backgr开发者_如何学Goound image with Javascript.
I can get urldata of IMG elements but how about this one ?
Thanks.
You can obtain the value of the background-image property with window.getComputedStyle
, then create a canvas and an image, apply the value to the src of the image, draw it on the canvas, and finally get the data ? =°
function getBgImageData(el,callback) {
var url,
image,
canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
// Allows el to be an element or an id
if(typeof el==='string') {
el = document.getElementById(el);
}
// Gets the value of the background-image property
url = window.getComputedStyle(el,null).backgroundImage;
// Removes the url("") part
url = url.substring(5,url.length-2);
// Creates the image
image = new Image();
image.src = url;
image.onload = function() {
canvas.width = image.width;
canvas.height = image.height;
// Draws the image
ctx.drawImage(image,0,0);
if(callback) {
// Passes the data to the callback function
callback(canvas.toDataURL());
}
};
}
getBgImageData('someId',function(data) {
alert(data);
});
(getComputedStyle
does not work in IE... but neither does Canvas)
精彩评论