我正在尝试在画布上制作简单的动画,试图通过更新 x 轴向右移动矩形,但它不起作用我不知道为什么?
我被困住了,我需要帮助和感谢?
类主
// 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;
loop = new Loop(canvas, display); // instance loop
// draw loop
function drawLoop() {
loop.player.point.x++;
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.point.x++; // trying to update x but the rect does not move
}
// 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;
}
}
矩形应该向右移动 1 个像素,谢谢。
对我来说
它有效,但你必须清除画布(首先绘制一个白色矩形(。此外,您忘记了 Size 类,因此未定义宽度和高度。
法典
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 {
constructor(canvas, display) {
this.display = display;
this.canvas = canvas;
this.point = new Point(20, 20);
this.size = new Size(100, 25);
}
// update
update() {
this.point.x++; // update x
}
// draw
draw() {
//remove previous
this.display.fillStyle = "#ffffff";
this.display.fillRect(0,0,400,400)
// draw rectangle using point and size
this.display.fillStyle = "#ff0000";
this.display.fillRect(this.point.x, this.point.y, this.size.w, this.size.h)
}
}
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
class Size {
constructor(w, h) {
this.w = w;
this.h = h;
}
}
let canvas = document.getElementById("canvas"); // get canvas
let display = canvas.getContext("2d"); // get context
let loop = new Loop(canvas, display); // instance loop
// draw loop
function drawLoop() {
loop.update(); // update
loop.draw(); // draw
requestAnimationFrame(drawLoop); // loop
}
// invoke
drawLoop();
<canvas id="canvas" width="400" height="200"></canvas>