简体   繁体   中英

How can I use a sprite sheet in JavaScript?

Hi I have already this code:

var refreshIntervalId;
var myImages = [
    "walking1.jpg",
    "walking2.jpg",
    "walking3.jpg",
    "walking4.jpg",
    "walking5.jpg",

];
var counter = 0;  


function switchImage() {
    $('#myImage').attr('src', myImages[counter]);
    counter += 1;

    if (counter == Number($("#counter").val())) {
        counter = 0;
        clearInterval(refreshIntervalId);



    }
}
$(document).ready(function() {
    $("#animationBtn").click(function(){
        refreshIntervalId = setInterval(switchImage, 50);
    }); 
});

But now I want instead of an image to play an spritesheet, is this possible? or do I have to change the whole code, yes? can someone help me with that?

A spritesheet is a sheet is basically an image file with a bunch of images, representing one (or several) animation sequence.

For example :

#nav li a {background-image:url('../img/image_nav.gif')}
#nav li a.item1 {background-position:0px 0px}
#nav li a:hover.item1 {background-position:0px -72px}
#nav li a.item2 {background-position:0px -143px;}
#nav li a:hover.item2 {background-position:0px -215px;}

Loading the image once and by changing the background-position displaying the other images in spritesheet.

Check this spritecow , an online tool(my favorite) to get the background-position of individual images in the spritesheet.

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