首页 > 解决方案 > 如何使用 html5 画布为多个形状的移动设置动画

问题描述

我的目标是使用 canvas 标签重新创建我在 Flash 中找到的此类项目。

这是我要复制的项目: https ://www.kongregate.com/games/Stillmerlin/the-empty-kingdom

我发现很难理解当形状必须逃离视野时如何为形状的运动设置动画。

这是我目前编译的代码,我设法使用键盘在各种矩形内移动正方形:https ://jsfiddle.net/mgus17db/

var canvas = document.querySelector("#demo_canvas");
var ctx = canvas.getContext("2d");

var pg = canvas.getContext("2d");

var xPos = 75;
var yPos = 75;

function draw() {
 ctx.rect(50, 50, 150, 100);
 ctx.stroke();

 ctx.rect(250, 50, 150, 100);
 ctx.stroke();

 ctx.rect(450, 50, 150, 100);
 ctx.stroke();

 ctx.rect(250, 200, 150, 100);
 ctx.stroke();

 pg.rect(xPos, yPos, 50, 50);
 pg.stroke();
};

draw();
console.log("x = " + xPos + ", y = " + yPos);


function move(e) {

 //ARROW KEY RIGHT
 if (e.keyCode == 39) {
  if (xPos == 75 && yPos == 75) {
   xPos += 225;
  }
  else if (xPos == 300 && yPos == 75) {
   xPos += 225;
  };
 };

 //ARROW KEY LEFT
 if (e.keyCode == 37) {
  if (xPos == 75 && yPos == 75) {
   xPos -= 0;
  }
  else if (xPos == 300 && yPos == 75) {
   xPos -= 225;
  }
  else if (xPos == 525 && yPos == 75) {
   xPos -= 225;
  };
 };

 //ARROW KEY UP
 if (e.keyCode == 38) {
  if (yPos == 75) {
   yPos -= 0;
  }
  else if (yPos == 225) {
   yPos -= 150;
  }
 };

 //ARROW KEY DOWN
 if (e.keyCode == 40) {
  if (yPos == 75 && xPos == 300) {
   yPos += 150;
  }
 };

 canvas.width = canvas.width;
 draw();
 console.log("x = " + xPos + ", y = " + yPos);
};

document.onkeydown = move;

标签: javascriptanimationhtml5-canvasshapes

解决方案


推荐阅读