0

I have a method in an object in JS that requires accessing a property inside the constructor. All the other property are ok except for one that is undefined. I don't know why it's undefined. I have an error in the console : "Cannot read property 'beginPath' of undefined at Canvas.draw ". When I console.log myCanvas.ctx I get undefined... I'm trying to make a simple canvas using object oriented programming. Here's my code.

class Canvas{
    construtor(){
       this.canvas = document.getElementById("canvas");
        this.ctx = this.canvas.getContext("2d");
        this.ctx.strokeStyle = "BADA55";
        this.ctx.lineWidth = 1;
        this.ctx.lineJoin = "round";
        this.ctx.lineCap = "round";
        this.isDrawing = false;
        this.lastX = 0;
        this.lastY = 0;
      

    }

    draw(x,y){
        if(!this.isDrawing)
      
            return;
          
            console.log(this);
            this.ctx.beginPath();
            this.ctx.moveTo(this.lastX, this.lastY); 
            this.ctx.lineTo(x, y);
            this.ctx.stroke(); 
            [this.lastX, this.lastY] = [x,y];
    }
    init(){
        canvas.addEventListener("mousemove", (e) => {
            this.draw(e.offsetX, e.offsetY);
        });
        canvas.addEventListener("mousedown", (e)=>{
        this.isDrawing = true;
        [this.lastX, this.lastY] = [e.offsetX, e.offsetY];
        });

       canvas.addEventListener("mouseup", ()=>this.isDrawing = false);
    }
}
let myCanvas = new Canvas;
myCanvas.init();
canvas{
        border:1px solid red;
        
    }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
        <canvas id="canvas"></canvas>
       
</body>
</html>
Mikev
  • 2,012
  • 1
  • 15
  • 27
Kelcodes
  • 11
  • 2

0 Answers0