当我以面向对象的方式尝试此代码时,它不起作用。我所有的console.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);
发布于 2019-09-13 19:22:47
欢迎来到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>
发布于 2019-09-14 20:12:28
好的,谢谢!实际上,它确实在起作用。这是因为我的html页面中还有其他元素,所以我的画布不在窗口的左上角。我已经弄清楚了如何使用offsetLeft和offsetTop方法使其工作。
https://stackoverflow.com/questions/57921800
复制相似问题