【问题标题】:how do i make a sprite running/sprint animation in html 5 canvas我如何在 html 5 画布中制作精灵运行/冲刺动画
【发布时间】:2020-02-04 01:01:26
【问题描述】:

我正在 html5 画布中创建一个 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();

【问题讨论】:

    标签: javascript html animation html5-canvas runtime


    【解决方案1】:

    加载一次图片

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

    加载图像一次,然后选择要渲染的图像。

    示例创建加载图片

    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 0

    示例将动画序列添加到数组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);
       }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-10
      • 1970-01-01
      • 2013-11-10
      • 1970-01-01
      • 2016-11-09
      • 2018-06-01
      • 2012-03-18
      • 2012-03-21
      相关资源
      最近更新 更多