我如何在 javascript 类 中使用 DOM 事件?
How can i use DOM events inside my javascript classes?
我正在尝试在我的 class 中创建一个函数,通过按 ArrowUp 键,它会变为真。但是,它只是说:“无法读取未定义的 属性 'key'?
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;
}
}
}
我的猜测是我必须在构造函数或构造函数的参数中定义某种 DOM 事件键,但我不知道如何?
在 p5.js you've just to define the function keyPressed()
中,如果按下按钮,将自动调用。您不需要定义任何 DOM 事件,p5.js 会为您完成这项工作,您只需 "use" 现有的回调,这些回调有据可查。
我建议阅读 p5.js - Get Started.
如果你想评估UP键是否被按下,那么你可以评估draw
中内置变量keyIsPressed
and keyCode
的状态:
function draw() {
if (keyIsPressed && keyCode === UP_ARROW) {
// [...]
}
// [...]
}
查看简短示例:
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>
我正在尝试在我的 class 中创建一个函数,通过按 ArrowUp 键,它会变为真。但是,它只是说:“无法读取未定义的 属性 'key'?
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;
}
}
}
我的猜测是我必须在构造函数或构造函数的参数中定义某种 DOM 事件键,但我不知道如何?
在 p5.js you've just to define the function keyPressed()
中,如果按下按钮,将自动调用。您不需要定义任何 DOM 事件,p5.js 会为您完成这项工作,您只需 "use" 现有的回调,这些回调有据可查。
我建议阅读 p5.js - Get Started.
如果你想评估UP键是否被按下,那么你可以评估draw
中内置变量keyIsPressed
and keyCode
的状态:
function draw() {
if (keyIsPressed && keyCode === UP_ARROW) {
// [...]
}
// [...]
}
查看简短示例:
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>