我正在尝试在画布上绘制一个简单的矩形并移动它,这就是为什么我在播放器内为动画和玩家类创建了循环类,我实例化了点类,但是当我尝试在播放器更新函数中使用它时,它会在控制台中给出未定义的原因?
我被困住了,我需要帮助。
类主
// import zone
import Player from "./player.js";
import Loop from "./loop.js";
// var zone
let canvas = document.getElementById("canvas"); // get canvas
let display = canvas.getContext("2d"); // get context
let loop;
// draw loop
function drawLoop() {
loop = new Loop(canvas, display); // instance loop
loop.update(); // update
loop.draw(); // draw
requestAnimationFrame(drawLoop); // loop
}
// invoke
drawLoop();
类循环
// import zone
import Player from "./player.js";
// class
export default class Loop {
// init
constructor(canvas, display) {
this.canvas = canvas;
this.display = display;
this.player = new Player(this.canvas, this.display);
}
// update
update() {
this.player.update();
}
// draw
draw() {
this.player.draw();
}
}
班级播放器
// import zone
import Size from "./size.js";
import Point from "./point.js";
// class
export default class Player {
constructor(canvas, display) {
this.display = display;
this.canvas = canvas;
this.point = new Point(200, 200);
this.size = new Size(100, 25);
}
// update
update() {
this.canvas.onclick = function(e) {
console.log(this.point.x);
};
}
// draw
draw() {
this.display.fillStyle = "#ffffff";
this.display.fillRect(this.point.x, this.point.y, this.size.w, this.size.h);
}
}
类点
export default class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
它应该返回位置 X(一个数字(。
您正在尝试在具有自己的"this"值的块中调用实例变量。但是,指针包含在对象的实例中。
箭头函数将保持词法范围,并允许您使用变量而不将"this"绑定到函数:
this.canvas.onclick = (e) => {
console.log(this.point.x);
};