Created
September 26, 2013 07:40
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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