简体   繁体   中英

Javascript sprite rotation animation on click

I'm trying to figure out how to create a rotating image effect using a sprite sheet in javascript. What I'm trying to do:

Two buttons:

Left button: Rotate 15 frames to the left. Right button: Rotate 15 frames to the right.

I realize that there are jquery plugins that would allow me to easily do this, but I want to try it from scratch. Beyond the general idea, I don't know where to proceed. Any tips would be greatly appreciated.

Check out this jsFiddle to see a working example


Based on your question, it sounds like you're trying to learn how to animate a sprite and not actually rotate a single image. If so, here is how you would animate a sprite. Note: this uses an image of a man running. In your question, you asked about a rotating image effect. In either case, you are simply looking at different slice of a sprite and then animation is solely dependent on the sprite. As long as your sprite displays a rotating image then the image will appear to rotate.

If you need a plugin to actually rotate an image, see here .

JavaScript

<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.1.js" type="text/javascript"></script> 
<script type="text/javascript">
var imgWidth = 240;
var imgHeight = 296;
var ximages = 6;
var yimages = 5;
var currentRow = 0;
var currentColumn = 0;

function MoveSprite(dir) { 
    if (dir == "left") {
        currentColumn--;
        if (currentColumn < 0)
        {
            currentColumn = ximages -1;
            if (currentRow == 0) {
                currentRow = yimages - 1;
            }
            else {
                currentRow--;
            }
        }   
    }
    else {
        currentColumn++;
        if (currentColumn == ximages) {
            currentColumn = 0;
            if (currentRow == yimages - 1) {
                currentRow = 0;
            }
            else {
                currentRow++;
            }
        }
    }
    $("#txtRow").val(currentRow);
    $("#txtColumn").val(currentColumn);
    $("#spritesheet").css("backgroundPosition", -imgWidth * currentColumn + "px " + -imgHeight * currentRow + "px"); 
}
</script>

HTML

<button onclick="MoveSprite('left');return false;">Move Left</button><button onclick="MoveSprite('right');return false;">Move Right</button>
<div id="spritesheet"></div>

CSS

<style type="text/css">
#spritesheet {
    height: 296px;
    width:240px;
    background-image:url('walking_spritesheet.png');
}
</style>

Sample Sprite (1440x1480):在此处输入图像描述

If you are familiar with MovieClip in flash, I made a library that gives you a similar interface in javascript. https://github.com/wolthers/SpriteClip.js

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