Skip to content

Instantly share code, notes, and snippets.

@silviopaganini
Last active December 11, 2015 14:08
Show Gist options
  • Save silviopaganini/4611967 to your computer and use it in GitHub Desktop.
Save silviopaganini/4611967 to your computer and use it in GitHub Desktop.
Creating a SpriteSheet Object (Div) for normal and retina devices
/*
USAGE:
img = new SSAsset(
{
fullSize : [512, 512]
x : 0,
y : 0,
width : 100,
height : 100,
image_1x_url : '/img/spritesheet_1x.png',
image_2x_url : '/img/spritesheet_1x.png'
},
$('.myDiv'));
CONSTRUCTOR
asset:
which asset ID on JSON
{
fullSize : background image 1x dimensions Array [x,y]
width : asset width
height : asset height
x : x position of the asset on SpriteSheet
y : y position of the asset on SpriteSheet
image_1x_url : background image 1x URL
image_2x_url : background image 2x URL
}
div :
jQuery reference to the target DIV
*/
var SSAsset = function (asset, div) {
var css, x, y, w, h;
// Divide the coordinates by 2 as retina devices have 2x density
x = Math.round(asset.x / 2);
y = Math.round(asset.y / 2);
w = Math.round(asset.width / 2);
h = Math.round(asset.height / 2);
// Create an Object to store CSS attributes
css = {
width : w,
height : h,
'background-image' : "url(" + asset.image_1x_url + ")",
'background-size' : "" + asset.fullSize[0] + "px " + asset.fullSize[1] + "px",
'background-position': "-" + x + "px -" + y + "px"
};
// If retina devices
if (window.devicePixelRatio === 2) {
/*
set -webkit-image-set
for 1x and 2x
All the calculations of X, Y, WIDTH and HEIGHT is taken care by the browser
*/
css['background-image'] = "-webkit-image-set(url(" + asset.image_1x_url + ") 1x, url(" + asset.image_2x_url + ") 2x)";
}
// Set the CSS to the DIV
div.css(css);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment