У меня есть метод в объекте в JS, который требует доступа к свойству внутри конструктора.Все остальные свойства в порядке, за исключением одного, которое не определено.Я не знаю, почему это не определено.У меня ошибка в консоли: «Не удается прочитать свойство 'beginPath' из неопределенного в Canvas.draw».Когда я console.log myCanvas.ctx я получаю неопределенный ... Я пытаюсь сделать простой холст, используя объектно-ориентированное программирование.Вот мой код.
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;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
</html>