gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 22:55:25 25 4
gpt4 key购买 nike

我尝试在对象中制作一个签名 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com