我正在尝试在画布中制作简单的动画,尝试通过更新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个像素。
答案 0 :(得分:0)
对我来说,它可以工作,但是您必须清除画布(首先绘制一个白色矩形)。另外,您忘记了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>