我想在画布中调用新对象而不删除旧对象。做这个的最好方式是什么?
我已经通过调用新对象编写了代码,但是删除了先前的代码。关键功能是update()。我考虑过关联数组,但是我不知道这是否是最佳方法。
const DIRECTION = {
RIGHT: 1,
IDLE: 0
}
let Package = {
new: function () {
return {
size: 50,
x: 0,
y: (this.canvas.height / 2 - 50),
speed: 3,
Move: DIRECTION.RIGHT
}
}
}
let Main = {
initialize: function () {
this.canvas = document.querySelector('canvas');
this.ctx = this.canvas.getContext('2d');
this.canvas.width = 1000;
this.canvas.height = 200;
this.canvas.style.width = 100 + '%';
this.canvas.style.height = 20 + 'vh';
this.color = '#4BBFC3';
this.legWidth = 25;
this.legHeight = 100;
this.package = Package.new.call(this);
Conveyor.draw();
Conveyor.loop();
},
draw: function () {
//Clear whole Canvas.
this.ctx.clearRect(
0,
0,
this.canvas.width,
this.canvas.height
);
//Draw empty Canvas.
this.ctx.fillStyle = this.color;
this.ctx.fillRect(
0,
0,
this.canvas.width,
this.canvas.height
);
//conveyor
this.ctx.fillStyle = "white";
this.ctx.fillRect(
0,
this.canvas.height / 2,
this.canvas.width,
this.canvas.height / 2 - 70
);
for (let legPosition = 0; legPosition < this.canvas.width; legPosition += 75) {
this.ctx.fillStyle = 'white';
this.ctx.fillRect(
legPosition,
this.canvas.height / 2,
this.legWidth,
this.legHeight
);
}
//package
this.ctx.fillStyle = 'black';
this.ctx.fillRect(
this.package.x,
this.package.y,
this.package.size,
this.package.size
)
},
update: function () {
if (this.package.Move === DIRECTION.RIGHT) {
this.package.x += this.package.speed;
}
if(this.package.x > 200) {
this.package = Package.new.call(this);
}
},
loop: function () {
Conveyor.update();
Conveyor.draw();
window.requestAnimationFrame(Conveyor.loop);
}
}
let Conveyor = Object.assign({}, Main);
Conveyor.initialize();
将调用新对象,但它将替换旧对象。