我试图在画布上绘制一个简单的矩形并将其移动,这就是为什么我在播放器内部实例化点类时为动画和播放器类创建循环类的原因,但是当我尝试在控制台中提供的播放器更新功能中使用它时不确定为什么?
我被困住了,我需要帮助。
主要班级
// 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();
}
}
Class Player
// 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);
}
}
Class Point
export default class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
它应该返回位置x(一个数字)。
答案 0 :(得分:0)
您正在尝试在具有自己的“ this”值的块内调用实例变量。但是,指针包含在对象的实例中。
箭头函数将保持词法作用域,并允许您使用变量而无需将“ this”绑定到函数:
this.canvas.onclick = (e) => {
console.log(this.point.x);
};