Skip to content

Instantly share code, notes, and snippets.

@dvidsilva
Created September 26, 2013 07:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dvidsilva/6710980 to your computer and use it in GitHub Desktop.
Save dvidsilva/6710980 to your computer and use it in GitHub Desktop.
Get all background images in a page and create a canvas/sprite with them, with plain js
document.getElementsByTagName("body")[0].innerHTML += '<canvas id=sprite ></canvas>';
var items = document.getElementsByTagName("*");
var c = document.getElementById("sprite");
c.width = 4000;
c.height = 10000;
c.style.border = '1px solid black';
var y = 0;
var x = 0;
var h = 0;
for (var i = items.length; i--;) {
var bi = getComputedStyle(items[i]).backgroundImage;
if(bi ){
var str = bi
str = str.replace("url(","");
str = str.replace(")","");
draw(str);
}
}
function draw(source) {
var ctx = document.getElementById('sprite').getContext('2d');
var img = new Image();
img.onload = function(){
if(img.width > x){
x = img.width;
}
console.log(y);
ctx.drawImage(img, 0, y, img.width, img.height);
y = img.height + y;
};
img.src = source;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment