我如何在 html 5 canvas 中制作精灵 running/sprint 动画

how do i make a sprite running/sprint animation in html 5 canvas

我正在 html5 canvas 中创建 2D 平台游戏。我正在尝试为精灵制作动画,以便它切换到 运行 图像和文具图像,以创建精灵是 运行 的错觉。我尝试根据帧数更改精灵图像,但它只显示精灵 运行 不到一秒钟。这不是我的完整代码。仅与 运行 动画相关的部分。

index.html:

 <!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Game</title>
    <style media="screen">
      #canvas {
        background-color: #87cefa;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas" width="800" height="600"></canvas>
  </body>
  <script type="text/javascript" src="index.js">

  </script>
</html>

index.js:

var canvas, ctx, player, playerPng, key, frameNo;
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
player = {
   w: 100,
   h: 200,
   x: 40,
   y: canvas.height - 20
}
playerPng = new Image();
frameNo = 0;
key = false;
function loop() {
   frameNo += 1;
   ctx.clearRect(0, 0, canvas.width, canvas.height);
   ctx.imageSmoothingEnabled = false;
   ctx.drawImage(playerPng, player.x, player.y, player.w, player.h);
   if(key === 39) {
      if(frameNo % 100 === 0){
         playerPng.src = "Running.png";
      } else {
         playerPng.src = "normal.png";
      }
   }
   if(key === false){
      playerPng.src = "normal.png";
   }
   window.requestAnimationFrame(loop);
}
window.addEventListener('keydown', function(e){
   key = e.keyCode;
});
window.addEventListener('keyup', function(e){
   key = false;
});
loop();

一次加载图像

首先不要在每次渲染时都加载图像。 image.src = "filenameORUrl" 加载图像。

加载一次图像然后select你想渲染哪一个。

示例创建加载图像

const running = new Image;   // create
const normal = new Image;
running.src = "Running.png"; //load
normal.src = "normal.png";

动画

要为图像添加动画,请将动画图像添加到数组中。设置一个变量来定义每个图像应出现多少帧,然后将 frameNum 除以该值并将其取整以获得图像索引。

动画图像示例

注意 (frameNo / runAnimFrames | 0) 中的 | 0(按位或 0)对结果进行取整。与 Math.floor(frameNo / runAnimFrames) 相同。应该只对小于 31 ** 2 - 1

的正数使用 OR 零

示例将动画序列添加到数组 runAnim 并在主渲染循环内显示动画,每个动画帧显示 30 帧 runAnimFrames(半秒)。减少数字以加快动画速度,增加以减慢速度。

您可以根据需要向动画数组添加任意数量的帧

const runAnim = [running, normal]; // add animation sequence to arr
const runAnimFrames = 30;   // number of frames to display each image in animation

// Inside main render loop
   if(key === 39) {
      const plyImg = runAnim[(frameNo / runAnimFrames | 0) % runAnim.length];
      ctx.drawImage(plyImg, player.x, player.y, player.w, player.h);
   } else {
      ctx.drawImage(normal, player.x, player.y, player.w, player.h);
   }