Получение urldata фонового изображения с помощью Javascript (возможно, с использованием canvas) - PullRequest
1 голос
/ 23 октября 2010

Предположим, что есть элемент DIV, и он имеет свойство CSS background-image.

Я хочу получить urldata (base64) фонового изображения с помощью Javascript.

Я могу получить urldata элементов IMG, но как насчет этого?

Спасибо.

1 Ответ

1 голос
/ 23 октября 2010

Вы можете получить значение свойства background-image с помощью window.getComputedStyle, затем создать холст и изображение, применить значение к источнику изображения, нарисовать его на холсте и, наконец, получить данные? = °

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 не работает в IE ... но не работает и Canvas)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...