Emre Kilic
Emre Kilic

Reputation: 3

google console can't find my already defined variable

This is the content inside draw.js file and the error seems to be related with line 11 and 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 file content

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

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

Upvotes: 0

Views: 36

Answers (1)

Caio Santos
Caio Santos

Reputation: 1805

Your function is declared as

snake(){ ... }

You should declare as

Snake(){ ... }

Full example ( I tested, it works! fillStyle was changed to black. )

<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>

Upvotes: 1

Related Questions