javascript fillRect未显示

y0u0uwnf  于 2023-01-11  发布在  Java
关注(0)|答案(1)|浏览(90)

我正在尝试编写一个关于滑雪板的游戏,但是到目前为止,当我尝试制作树(绿色矩形)时,它们没有出现。
代码:

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

canvas.width = 1000;
canvas.height = 800;

var x = canvas.width / 2,
  speed = 0.1,
  size = 5,
  alive = 1,
  keys = [];

function player() {
  if (alive === 1) {
    if (keys[37] || keys[65]) {
      x -= 3;
    }
    if (keys[39] || keys[68]) {
      x += 3;
    }

    if (x > canvas.width) {
      x = canvas.width;
    }
    if (x < 0) {
      x = 0;
    }

    ctx.beginPath();
    ctx.fillStyle = "black"
    ctx.arc(x, 100, size, 0, Math.PI * 2);
    ctx.fill();

  }

}

function tree() {
  var treeX = Math.floor(Math.random() * (canvas.width + 1)) + 25;
  var treeY;
  if (treeY < 1) {
    treeY = canvas.height;
  } else {
    treeY -= speed;
  }

  ctx.fillStyle = "green";
  ctx.fillRect(treeX, treeY, 5, 8);

}

function update() {
  requestAnimationFrame(update);
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  player();

  tree();

}

update();

document.body.addEventListener("keydown", function(e) {
  keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function(e) {
  keys[e.keyCode] = false;
});
<canvas id="canvas"></canvas>

我试着切换事情的顺序,并使用控制台,看看树在哪里,但没有工作。

w51jfk4q

w51jfk4q1#

对于player,您在函数外部的一些不同变量中跟踪 * state *。
要使树能够更新,还必须跟踪其状态。
这里有一个方法可以做到这一点:

  • 将值作为参数传递,而不是总是在函数中重新初始化treeXtreeY
  • 更新树状态后,返回其xy坐标
  • tree函数之外,跟踪树列表。
  • update中,将树列表替换为更新的树。

下面是一个正在运行的例子:

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

canvas.width = 400;
canvas.height = 200;

var x = canvas.width / 2,
  speed = 1,
  size = 5,
  alive = 1,
  keys = [],
  trees = [ tree(), tree(), tree() ];

function player() {
  if (alive === 1) {
    if (keys[37] || keys[65]) {
      x -= 3;
    }
    if (keys[39] || keys[68]) {
      x += 3;
    }

    if (x > canvas.width) {
      x = canvas.width;
    }
    if (x < 0) {
      x = 0;
    }

    ctx.beginPath();
    ctx.fillStyle = "black"
    ctx.arc(x, 100, size, 0, Math.PI * 2);
    ctx.fill();
  }

}

function tree(
  treeX = Math.floor(Math.random() * (canvas.width + 1)),
  treeY = Math.floor(Math.random() * (canvas.height + 1))
) {
  if (treeY < 1) {
    treeY = canvas.height;
  } else {
    treeY -= speed;
  }

  ctx.fillStyle = "green";
  ctx.fillRect(treeX, treeY, 5, 8);
  
  return [ treeX, treeY ];
}

function update() {
  requestAnimationFrame(update);
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  player();
  trees = trees.map(([x, y]) => tree(x, y));
}

update();

document.body.addEventListener("keydown", function(e) {
  keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function(e) {
  keys[e.keyCode] = false;
});
* { margin: 0; }
canvas { border: 1px solid red; }
<canvas id="canvas"></canvas>

相关问题