为什么我的画布签名不起作用?我必须在定向对象javascript中执行此操作.无定向对象中的相同代码正在工作



当我以定向对象的方式尝试此代码时,它不起作用。我所有的控制台.log给出答案。我不明白为什么屏幕上没有画任何东西。相同的代码以无面向对象的方式工作。

class Canvas {
constructor(idCanvas, width, height){
this.canvas=document.getElementById(idCanvas);
this.ctx=this.canvas.getContext("2d");
this.drawing= false;
this.canvas.width=width;
this.canvas.height=height;
this.mouseEvents();
}
startPosition(){
this.drawing= true;
console.log("hi!");
}
finishedPosition(){
this.drawing= false;
console.log("hello!");
}
draw(e){
if(!this.drawing) return; // si on ne dessine pas rien ne se passe
this.ctx.lineWidth=10;
this.ctx.lineCap="round";
this.ctx.strokeStyle="green";
this.ctx.lineTo(e.clientX, e.clientY);// clientX et clientY vont donner la position de la souris
this.ctx.stroke();
console.log("draw!");
console.log(this.drawing);
console.log(this.ctx);
console.log(this.ctx.stroke);
}
mouseEvents(){
this.canvas.addEventListener("mousedown",()=>this.startPosition());
this.canvas.addEventListener("mouseup",()=>this.finishedPosition());
this.canvas.addEventListener("mousemove",(e)=>this.draw(e));
console.log("ok!");
}
}
const newCanvas = new Canvas("canvas",150, 150)
console.log(newCanvas);

欢迎来到 SO folk,您的片段没有画布 html 元素。除此之外,它正在工作。见下文。

class Canvas {
constructor(idCanvas, width, height){
this.canvas=document.getElementById(idCanvas);
this.ctx=this.canvas.getContext("2d");
this.drawing= false;
this.canvas.width=width;
this.canvas.height=height;
this.mouseEvents();
}
startPosition(){
this.drawing= true;
console.log("hi!");
}
finishedPosition(){
this.drawing= false;
console.log("hello!");
}
draw(e){
if(!this.drawing) return; // si on ne dessine pas rien ne se passe
this.ctx.lineWidth=10;
this.ctx.lineCap="round";
this.ctx.strokeStyle="green";
this.ctx.lineTo(e.clientX, e.clientY);// clientX et clientY vont donner la position de la souris
this.ctx.stroke();
console.log("draw!");
console.log(this.drawing);
console.log(this.ctx);
console.log(this.ctx.stroke);
}
mouseEvents(){
this.canvas.addEventListener("mousedown",()=>this.startPosition());
this.canvas.addEventListener("mouseup",()=>this.finishedPosition());
this.canvas.addEventListener("mousemove",(e)=>this.draw(e));
console.log("ok!");
}
}
const newCanvas = new Canvas("canvas",150, 150)
console.log(newCanvas);
<canvas id="canvas"></canvas>

是的,谢谢!实际上它确实在起作用。这是因为我的 html 页面中还有其他元素,所以我的画布不在窗口的左上位置。我已经弄清楚了如何使用offsetLeft和offsetTop方法使其工作。

最新更新