Javascript sprite rotation click animation

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

Two buttons:

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

I understand that there are jquery plugins that will allow me to easily do this, but I want to try it from scratch. Besides the general idea, I do not know where to start. Any advice would be greatly appreciated.

+3
source share
3 answers

Take a look at jsFiddle to see a working example.


, , . , . : , . . , . , .

, . .

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>

(1440x1480): enter image description here

+7

MovieClip Flash, , javascript. https://github.com/wolthers/SpriteClip.js

+1

All Articles