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

标签 javascript object canvas constructor

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

函数绘制中的问题。

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>

最佳答案

您的事件处理函数需要绑定(bind)到实例。所以在构造函数中这样做:

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

这应该可以解决您的问题。

关于javascript - 我的上下文是在构造函数中定义的,而不是在函数中定义的。无法读取 HTMLCanvasElement.draw 处未定义的属性 'beginPath',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56706330/

相关文章:

javascript - 如何在谷歌地图的风格上加载一个巨大的图像?

javascript - 使用外部文件的文件夹制作网页

javascript - 在 Canvas 上打印倾斜文本而不旋转整个 Canvas

javascript - 类似 iCal 的日历 jQuery

javascript - 检查数组元素是否存在,如果不存在,则使用 JavaScript 跳到下一个

javascript - 在 javascript 中是否有比这更好的方法来实现函数式递归 findById?

java - 从对象中的对象调用对象中的方法

javascript - 从对象中查找和删除项目

javascript - JSON.stringify(object) 不正确

jquery - 这位作者是如何在文本中制作均衡器效果的?