我的上下文是在构造函数中定义的,而不是在函数中定义的。无法读取 HTMLCanvasElement.draw 上未定义的属性"beginPath"



我尝试在对象中制作签名画布,我在构造函数中声明上下文,但他在函数中未定义。如何在函数上声明我的上下文?

函数绘制中的问题。

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);
    }
  }

索引部分

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

事件处理程序函数需要绑定到实例。所以在构造函数中这样做:

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

这应该可以解决你。

相关内容

最新更新