我正在尝试使用 canvas 显示形状,但它们没有显示

I'm trying to display shapes using canvas and they aren't showing up

我正在开发一个简单的游戏(遵循 Zenva Academy 上的教程),尽管我已经按照 T 的说明进行操作,但我似乎无法显示我的 canvas 形状在浏览器中。这是我到目前为止的代码:

var canvas = document.getElementByID('myCanvas');
var ctx = canvas.getContext('2d');

let screenWidth = 1000;
let screenHeight = 500;

class GameCharacter {
  constructor(x, y, width, height, color) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    this.color = color;
  }
}

var blueSquare = new GameCharacter(
  50, 50, 50, 50, "rgb(0, 0, 255)"
);
var rectangle = new GameCharacter(
  75, 75, 100, 50, "rgb(0, 255, 0)"
);
var redSquare = new GameCharacter(
  100, 50, 50, 50, "rgb(255, 0, 0)"
);

var draw = function() {
  ctx.clearRect(0, 0, screenWidth, screenHeight);

  ctx.fillStyle = "rgb(0, 0, 255)";
  ctx.fillRect(blueSquare.x, blueSquare.y, blueSquare.width, blueSquare.height);

  ctx.fillStyle = rectangle.color;
  ctx.fillRect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);

  ctx.fillStyle = redSquare.color;
  ctx.fillRect(redSquare.x, redSquare.y, redSquare.width, redSquare.height);

}

var step = function() {
  draw();

  window.requestAnimationFrame(step);
}
canvas {
  border: 4px solid green;
  background-color: yellow;
}
<canvas id='myCanvas' width='1000' height='500'></canvas>

我对此还是很陌生,这是我在论坛上提出的第一个问题。如果我做错了什么,请告诉我。哈哈!

我正在使用:

OS: Windows 10 专业版 64 位

浏览器: 尝试了 Chrome 和 Microsoft Edge

代码编辑器: Sublime Text 3

一个简单的错字 - 你写了 getElementByID,而你应该写 getElementById。 (这会立即显示在浏览器的开发人员工具控制台中。)

然后,您需要调用 step() 一次才能开始。

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

let screenWidth = 1000;
let screenHeight = 500;

class GameCharacter {
  constructor(x, y, width, height, color) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    this.color = color;
  }
}

var blueSquare = new GameCharacter(
  50, 50, 50, 50, "rgb(0, 0, 255)"
);
var rectangle = new GameCharacter(
  75, 75, 100, 50, "rgb(0, 255, 0)"
);
var redSquare = new GameCharacter(
  100, 50, 50, 50, "rgb(255, 0, 0)"
);

var draw = function() {
  ctx.clearRect(0, 0, screenWidth, screenHeight);

  ctx.fillStyle = "rgb(0, 0, 255)";
  ctx.fillRect(blueSquare.x, blueSquare.y, blueSquare.width, blueSquare.height);

  ctx.fillStyle = rectangle.color;
  ctx.fillRect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);

  ctx.fillStyle = redSquare.color;
  ctx.fillRect(redSquare.x, redSquare.y, redSquare.width, redSquare.height);

}

var step = function() {
  draw();

  window.requestAnimationFrame(step);
}

step();
canvas {
  border: 4px solid green;
  background-color: yellow;
}
<canvas id='myCanvas' width='1000' height='500'></canvas>