我在JS中的对象中有一个方法,该方法需要访问构造函数中的属性。除未定义的属性外,其他所有属性都可以。我不知道为什么它是不确定的。 我在控制台中出现错误:“无法读取未定义的属性'beginPath' 在Canvas.draw“。当我console.log myCanvas.ctx时,我无法定义... 我正在尝试使用面向对象的编程制作一个简单的画布。 这是我的代码。
public static void main(String args[]) {
new SpringApplicationBuilder(Application.class)
.initializers(new DemoApplicationContextInitializer())
.run(
}
class Canvas{
construtor(){
this.canvas = document.getElementById("canvas");
this.ctx = this.canvas.getContext("2d");
this.ctx.strokeStyle = "BADA55";
this.ctx.lineWidth = 1;
this.ctx.lineJoin = "round";
this.ctx.lineCap = "round";
this.isDrawing = false;
this.lastX = 0;
this.lastY = 0;
}
draw(x,y){
if(!this.isDrawing)
return;
console.log(this);
this.ctx.beginPath();
this.ctx.moveTo(this.lastX, this.lastY);
this.ctx.lineTo(x, y);
this.ctx.stroke();
[this.lastX, this.lastY] = [x,y];
}
init(){
canvas.addEventListener("mousemove", (e) => {
this.draw(e.offsetX, e.offsetY);
});
canvas.addEventListener("mousedown", (e)=>{
this.isDrawing = true;
[this.lastX, this.lastY] = [e.offsetX, e.offsetY];
});
canvas.addEventListener("mouseup", ()=>this.isDrawing = false);
}
}
let myCanvas = new Canvas;
myCanvas.init();
canvas{
border:1px solid red;
}