简体   繁体   中英

Javascript animation scale sprite

在此处输入图片说明

This is the sprite I am using to animate an object through css. Every frame is 224px in width so the background-position property of the div is incremented by -224px every frame and the cycle goes on. The problem is that the width of my div is not fixed. I use percentage width of the div to stay resolution independent. So I want my 224px wide frame to scale over the width of the div and move left the same amount every frame. Hope it is clear to you. Here is the JS function used to animate the div.

function moveTail() {
    if ( typeof moveTail.counter == 'undefined' ) {
        moveTail.counter = 0;
        moveTail.object = $('#genietail');
    }

    if( moveTail.counter == 42 )
        moveTail.counter = -1;
    ++moveTail.counter;
    moveTail.object.css('background-position', moveTail.counter*-224 + "px 0px" );
}

There are two ways of scaling a sprite image.

The first one is to play with the background-size CSS attribute. If your sprite size is for example 100px by 100px, by default background-size will take the value 100px 100px , but if you set it to 200px 200px it will double the image size that will be displayed.

In your case it would look like this :

var spriteSize = { height: 224, width : 224 * 20 };
var imageSize = { height: 224, width : 224 };
var backgroundWidth = Math.floor((moveTail.object.width()  / imageSize.width) * spriteSize.width);
var backgroundHeight = moveTail.object.height();

moveTail.object.css("background-size", backgroundWidth + "px " +  backgroundHeight + "px");
moveTail.object.css('background-position', moveTail.counter * -moveTail.object.width() + "px 0px" );

The second one is to use the CSS 3 attribute transform with scaleX and scaleY . If you want a div to double the size that is displayed you can do in CSS transform: scaleX(2) scaleY(2) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM