Javascript 我的上下文是在构造函数中定义的,但不是在函数中定义的。无法读取属性';beginPath';在HTMLCanvasElement.draw中未定义的
我尝试在对象中创建签名画布,在构造函数中声明上下文,但在函数中未定义。如何在函数上声明上下文 函数绘制中的问题Javascript 我的上下文是在构造函数中定义的,但不是在函数中定义的。无法读取属性';beginPath';在HTMLCanvasElement.draw中未定义的,javascript,object,canvas,constructor,Javascript,Object,Canvas,Constructor,我尝试在对象中创建签名画布,在构造函数中声明上下文,但在函数中未定义。如何在函数上声明上下文 函数绘制中的问题 class Canvas{ constructor(dom, erase, color, lineJoin, lineCap, lineWidth){ this.canvas = document.getElementById(dom); this.erase = document.getElementById(erase); this.c
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>
var myCanvas=新画布(“签名”、“重新开始”、“000000”、“圆形”、“圆形”,3);
事件处理程序函数需要绑定到实例。因此,请在构造函数中执行此操作:
this.penDown.bind(this);
this.draw.bind(this);
this.noDown.bind(this);
this.eraseCanvas.bind(this);
那会使你恢复健康。不客气。请注意:另外,我注意到<代码> EraseChanVar()<代码>错误地引用了<代码> CTX——您将要将其更改为<代码>。