0

Every time I invoke clearRect in context it throws 'Uncaught TypeError: Cannot read properties of undefined (reading 'clearRect')', context isn't undefined (checked using console.log(game.context)). This error confuses me a lot

There is code of my script:

class Game {
    constructor(canvas_width, canvas_height) {
        this.canvas = document.createElement("canvas")
        this.canvas.width = canvas_width
        this.canvas.height = canvas_height
       

        this.context = this.canvas.getContext("2d")

        document.body.insertBefore(this.canvas, document.body.childNodes[0])

        this.interval = setInterval(this.update, 20)

        this.components = []
    }

    update() {
        this.context.clearRect(0, 0,  this.canvas.width, this.canvas.height)
        this.components.forEach(component => {
            component.updateComponent()
            component.drawComponent(context)
        });
    }
}

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

    updateComponent() {
        
    }

    drawComponent(context) {
        context.fillStyle = this.color
        context.fillRect(this.x, this.y, this.width, this.height)
    }
}

var game = new Game(780, 350)
var rect = new GameComponent(50, 50, 64, 64, "#000055")
game.components.push(rect)
danilwhale
  • 13
  • 2

0 Answers0