How can I scale/stretch/skew a sprite from a sprite sheet with javascript?

Tgwizman picture Tgwizman · Dec 9, 2011 · Viewed 7.8k times · Source

Some background: I am making a raycaster, well... was making. But I decided to change it up a bit. I started off going on creating the ray caster and decided it would be so much easier to just display an icon and stretch/skew it instead of just moving around a bunch of pixels.

My question is: How can I scale/stretch/skew a sprite from a sprite sheet with javascript?

I basically am wanting to get a 16px by 16px image from a sprite image, and position it, scale it, turn it, and skew it with javascript. How should I go about doing that?

If this helps, I was thinking about connecting three versions of that image to give it the impression of a 3D block moving around in a 3D space without actually using 3D.

Answer

stot picture stot · Jan 2, 2013

Most probably the easiest way is to use the background-size css property. As most modern browsers (IE 9+, FF4+, Safari4+, Chrome3+) support it you can do the following:

html:

<div id="mySprite">
</div>

css:

#mySprite{
    height: 80px; /* 64px * 1.25 */
    width: 80px;  /* 64px * 1.25 */
    background-image:url(my.png);
    background-position: -0px -560px; /* pick specific one at -448px * 1.25 */
    background-size:640px 640px; /* scale image to 512px * 1.25 */
}

The spritesheet has sprites with size 64x64px on it and scales them to 80x80px. See live example here: http://jsfiddle.net/Zgr5w/1/

As @Prusse said: you can use transform: scale() also but it has some drawbacks: browser support, additional position transformation, alignment with other elements may be broken:

#mySprite{
    height: 64px;
    width: 64px;
    background-image:url(my.png);
    background-position: -0px -448px;
    transform:scale(1.25);
    /* additional to compensate the position shift */
    position:relative;
    top:10px;
    left:10px;
}

see live example of the above two approaches here: http://jsfiddle.net/Zgr5w/1/