Total Pageviews

Monday 25 May 2015

Sprite Sheet Animation Using JavaScript and HTML5

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Sprite Sheet Animation</title>
</head>

<body>
<canvas id="myCanves" width="100" height="100">
<!-- Insert fallback content here -->
</canvas>
<script>
        var _width = 100;
var _height = 100;
var _frame = 4;
var _currentFrameCount = 0;
var ctx;

canvas = document.getElementById("myCanves");
ctx = canvas.getContext("2d");

var img = new Image();
img.src = "sprite.png";
img.onload = draw;

function draw ()
{
   ctx.clearRect(0, 0, _width, _height);   //to clear previously draw sprite before drawing new.
   ctx.drawImage(img, 0, _height * _currentFrameCount, _width, _height, 0, 0, _width, _height);  //to draw a sprite sheet with given height width and co-ordinates.

if(_currentFrameCount == _frame)
{
  _currentFrameCount = 0;
}
else
{
   _currentFrameCount++;
}
    }
setInterval(draw, 100);    // to call a draw function in a regular interval.

</script>
</body>
</html>

No comments:

Post a Comment

Microsoft Logo using flexbox and Reactjs

 <!DOCTYPE html> <html> <head>     <script src="https://unpkg.com/react@18/umd/react.development.js" crossori...