views:

23

answers:

1

Let's assume there is a DIV element and it has CSS background-image property.

I want to get urldata(base64) of the background image with Javascript.

I can get urldata of IMG elements but how about this one ?

Thanks.

+1  A: 

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)

Golmote
Wouldn't this raise a security exception if the image is hosted on a different domain (well, even on the same domain but different subdomain)
ArtBIT
I have leveraged permissions(it is not a web application)
Ozgur
@Golmote another important thing is whether creating an image element will reload the actual image(or use it from cache). I will test it now.
Ozgur
@ArtBIT : Yes, in effect, I guess it could raise security exception running this code with "file://..." url or with cross-domain url.@Ozgur : If you want to force the browser to reload it (and not use it form the cache), you could add a random parameter to the url.`image.src = url+(new Date()).getTime();`
Golmote