简体   繁体   English

如何在我的 javascript 类中使用 DOM 事件?

[英]How can i use DOM events inside my javascript classes?

I am trying to make a function inside my class, where by pressing the ArrowUp key, it will become true.我正在尝试在我的 class 中制作一个 function,通过按下 ArrowUp 键,它就会变为真。 However, it just says: "Cannot read property 'key' of undefined?但是,它只是说:“无法读取未定义的属性'键'?

class Boks{
  constructor(x,y,w,h,r,k){
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.r = r;
    this.k = k;
  }

  visSnake(){
    rect(this.x,this.y,this.w,this.h)
  }

  moveSnake(){
    this.x = this.x + speed;
  }

  keyb(event){
    if(event.key === "ArrowUp"){
      return true;
    }
  }
}

My guess is that I have to define some sort of DOM event key in the constructor or parameter to the constructor, but i dont know how?我的猜测是我必须在构造函数或构造函数的参数中定义某种 DOM 事件键,但我不知道怎么做?

In p5.js you've just to define the function keyPressed() which is automatically called, if an button is pressed.p5.js 中,您只需定义 function keyPressed()如果按下按钮,则会自动调用。 You don't need to define any DOM event, p5.js does the job for you, you've just to "use" the existing callbacks, which are well documented.您不需要定义任何 DOM 事件,p5.js 会为您完成这项工作,您只需“使用”现有的回调,这些回调有据可查。
I recommend to read p5.js - Get Started .我建议阅读p5.js - 入门

If you want to evaluate if the UP key is pressed, then you can evaluate the state of the built in variable keyIsPressed and keyCode in draw :如果要评估是否按下了UP键,则可以评估 draw 中内置变量keyIsPressedkeyCodedraw

function draw() {

    if (keyIsPressed && keyCode === UP_ARROW) {
        // [...]
    }

    // [...]
}

See the short example:请参阅简短示例:

 let x=0, y=0, w=20, h=20; function setup(){ createCanvas(window.innerWidth-20,window.innerHeight-20) x = width/2; y = height/2; frameRate(10); } function draw(){ if (keyIsPressed && keyCode === LEFT_ARROW){ if (x > 0) { x -= w; } } if (keyIsPressed && keyCode === RIGHT_ARROW){ if (x < width-w) { x += w; } } if (keyIsPressed && keyCode === UP_ARROW) { if (y > 0) { y -= h; } } if (keyIsPressed && keyCode === DOWN_ARROW){ if (y < height-h) { y += h; } } background(0); stroke(255); fill(255); rect(x, y, w, h); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM