Javascript画布动画小精灵行走

时间:2018-07-23 23:20:53

标签: javascript animation canvas sprite

我试图让精灵在画布上浏览背景图像。理想情况下,我会在一张画布上完成所有操作,但是使用两张画布似乎更有效,更容易。

到目前为止我所拥有的:

Fiddle 1

Fiddle 2

提琴1的代码,用于最简单的动画形式:

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

var spritePosition = 0;
var spriteWidth = 50;
var spriteHeight = 225;
var spriteCount = 17;
var spritePlayCount = 0;
var maxSpritePlays = 3;

var sheet = new Image();
sheet.onload = function () {
    animate();
}
sheet.src = "https://s33.postimg.cc/dapcxzmvj/sprite_walk.png";

var fps = 15;



function animate() {
    setTimeout(function () {

        if (spritePlayCount < maxSpritePlays) {
            requestAnimationFrame(animate);
        }

        // Drawing code goes here
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(sheet,
        spritePosition * spriteWidth, 0, spriteWidth, spriteHeight,
        0, 0, spriteWidth, spriteHeight);

        spritePosition++;
        if (spritePosition > spriteCount - 1) {
            spritePosition = 0;
            spritePlayCount++;
        }

    }, 1000 / fps);
}

我希望能够使它正确行走,并了解其工作原理。我看到两者都沿sprite.widthsprite.height的方式使用,我认为它们分别为width/columnsheight/rows,但它们似乎无法正常工作。

1 个答案:

答案 0 :(得分:1)

您的坐标全都错了。您的spriteWidth和spriteHeight值与spritesheet的所有值都不匹配。

此外,您的逻辑仅更新x轴,而将子画面工作表设置为多行。
您需要更新此逻辑,以便同时更新x和y源位置。

最后,不要像这样混合setTimeout和requestAnimationFrame。他们永远不会相处得很好。 要达到15FPS,您可以很容易地运行一个requestAnimationFrame循环,该循环将以60FPS的速度触发,并仅每四帧绘制一次(60FPS / 4 => 15FPS)。

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

var xIndex = 0;
var yIndex = 0;
var cols = 5;
var rows = 4;
var spriteWidth = 265;
var spriteHeight = 200;

var sheet = new Image();
sheet.onload = function() {
  animate();
}
sheet.src = "https://i.stack.imgur.com/eL5yV.png";
var frame = 0;

function animate() {
  requestAnimationFrame(animate);
  // 60FPS / 4 => 15FPS
  if ((++frame) % 4 > 0) return;

  ctx.clearRect(0, 0, canvas.width, canvas.height);
  // update the current column
  xIndex = (xIndex + 1) % cols;
  // update the current row if x is 0
  yIndex = xIndex === 0 ? (yIndex + 1) % rows : yIndex;
  // three cells are empty on the last row...
  if (yIndex === (rows - 1) && xIndex === 2)
    xIndex = yIndex = 0;
  // update both sourceX and sourceY
  ctx.drawImage(sheet,
    xIndex * spriteWidth, yIndex * spriteHeight, spriteWidth, spriteHeight,
    0, 0, spriteWidth, spriteHeight);
}
<canvas id="canvas" width=350 height=350></canvas>