My context is defined in constructor, but not in function. Cannot read property 'beginPath' of undefined at HTMLCanvasElement.draw

Viewed 113

I try to make a signature canvas in object,i declare the context in constructor but he's undefined in function. How to declare my context on function?

Problem in function draw.

class Canvas{

    constructor(dom, erase, color, lineJoin, lineCap, lineWidth){
      this.canvas = document.getElementById(dom);
      this.erase = document.getElementById(erase);
      this.ctx = this.canvas.getContext("2d");
      console.log(this.ctx);
      this.ctx.strokeStyle = color;
      this.ctx.lineJoin = lineJoin;     
      this.ctx.lineCap = lineCap;      
      this.ctx.lineWidth = lineWidth;           
      this.penX = 0;
      this.penY = 0;
      this.down = false;
      this.canvas.addEventListener("mousedown", this.penDown);
      this.canvas.addEventListener("mousemove", this.draw);
      this.canvas.addEventListener("mouseup", this.noDown);
      this.canvas.addEventListener("mouseout", this.noDown);
      this.erase.addEventListener("click", this.eraseCanvas);
     };

    noDown(){
      this.down = false;
    }

    draw(e){
      if(!this.down) return;
      this.ctx.beginPath();
      this.ctx.moveTo(this.penX, this.penY);
      this.ctx.lineTo(e.offsetX, e.offsetY);
      this.ctx.stroke();
      this.penX = e.offsetX;
      this.penY = e.offsetY;
    }

    penDown(e){
      this.down = true;
      this.penX = e.offsetX;
      this.penY = e.offsetY;
    }

    eraseCanvas(){
      ctx.clearRect(0, 0, 200, 100);
    }

  }

index part

<script>
   var myCanvas = new Canvas("signature", "recommencer", "#000000", "round", "round", 3);
</script>
1 Answers

Your event handler functions need to be bound to the instance. So do this in the constructor:

this.penDown.bind(this);
this.draw.bind(this);
this.noDown.bind(this);
this.eraseCanvas.bind(this);

That should fix you up.

Related