0

这是 draw.js 文件中的内容,错误似乎与第 11 行和第 13 行有关

const canvas = document.querySelector(".canvas");
const ctx = canvas.getContext("2d");
const scale = 10;
const rows = canvas.height / scale;
const columns = canvas.width / scale;

console.log("hello world")
var snake;

(function setup() {
  snake = new Snake();
  snake.draw();
}())

snake.js 文件内容

function snake() {
  this.x = 0;
  this.y = 0;

  this.draw = function() {
    ctx.fillStyle = "#FFFFFF";
    ctx.fillRect(this.x, this.y, scale, scale);
  }
}
4

1 回答 1

1

您的函数声明为

snake(){ ... }

你应该声明为

Snake(){ ... }

完整示例(我测试过,它有效!fillStyle 已更改为黑色。)

<html>

<body>
    <canvas class="canvas"></canvas>
    <script>
        function Snake() {
            this.x = 0;
            this.y = 0;

            this.draw = function () {
                ctx.fillStyle = "#000000";
                ctx.fillRect(this.x, this.y, scale, scale);
            }
        }
        const canvas = document.querySelector(".canvas");
        const ctx = canvas.getContext("2d");
        const scale = 10;
        const rows = canvas.height / scale;
        const columns = canvas.width / scale;

        console.log("hello world")
        var snake;

        (function setup() {
            snake = new Snake();
            snake.draw();
        }())
    </script>
</body>

</html>
于 2020-04-20T20:57:46.260 回答