我目前正在从事一个有角度的项目,但我不理解错误消息。 错误的发生方式:触发mouseevent(mousedown:仅是mouseclick事件)时,我调用mousedown方法,在此方法中,将调用方法addNode并发生错误
Typerror:您的函数this.addNode()不是HTMLCanvasElement上的函数
export class Graph {
private ctx : CanvasRenderingContext2D;
private canvas: HTMLCanvasElement;
private readonly width: number;
private readonly height: number;
nodes: Node[] = [];
constructor(canvas: HTMLCanvasElement){
this.canvas = canvas;
this.ctx = this.canvas.getContext('2d');
this.width = canvas.width;
this.height = canvas.height;
this.nodes = [];
canvas.addEventListener('mousedown', this.onDown, false);
this.draw1();
}
onDown(e:MouseEvent){
***this.addNode(e.offsetX,e.offsetY);*** //This Line causes the error
console.log("LOG LOG " + e.offsetX + ", " + e.offsetY);
console.log("My Array: " + this.nodes.length);
}
addNode(x:number,y:number){
this.nodes.push(new Node(x,y));
}
draw1():void{
// console.log("Should be drawing");
//console.log("Node legnth : " + this.nodes.length);
this.nodes.forEach(node => {
console.log("Why you not doing");
this.ctx.fillStyle = "green";
this.ctx.beginPath();
this.ctx.arc(node.x,node.y,25,0,2*Math.PI);
this.ctx.stroke();
this.ctx.fill();
});
window.requestAnimationFrame(()=>this.draw1());
}
}
class Node{
x:number;
y:number;
constructor(x:number,y:number){
this.x = x;
this.y = y;
}
}
我先谢谢大家:)
答案 0 :(得分:0)
尝试对方法function reload_pycharm_projects() {
cd $path_to_code_home
echo 'Running PyCharm...'
charm &
sleep 16 # wait 16s for PyCharm window to be opened; put in the time suitable on your machine
# open pycharm projects - list all projects of your interest below
echo 'Loading projects...'
charm p1
charm p2
charm p3
sleep 90 # wait 90s for all project load & index/cache refreshed; put in more time as you want
cd --
echo 'Closing Pycharm...'
kill -9 $(ps x | grep -E .+java.+PyCharm | awk '{print $1}') # kill pycharm window
exit
}
使用箭头函数将onDown()
的上下文保留到类this
:
Graph
或者,如果模板中存在实际的onDown = (e: MouseEvent) => {
***this.addNode(e.offsetX,e.offsetY);*** //This Line causes the error
console.log("LOG LOG " + e.offsetX + ", " + e.offsetY);
console.log("My Array: " + this.nodes.length);
}
元素,则可以使用<canvas>
代替在(mousedown)
中手动添加事件处理程序。
希望有帮助!
答案 1 :(得分:0)
尝试这样
canvas.addEventListener('mousedown', (e) => this.onDown(e), false);