Élément de base
class AnimatedBloc {
constructor(elt, {speed = 1} = {} ) {
this.elt = elt;
// initial CSS
this.initPosition( speed );
}
initPosition( speed ) {
if (this.elt) {
const {
left,
top
} = this.elt.getBoundingClientRect();
// CSS
this.cssX = left;
this.cssY = top;
this.x = 0;
this.y = 0;
this.speed = speed;
}
}
render() {
this.elt.style.cssText = `left:${this.x+this.cssX}px`;
//ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
}
update() {
this.x = this.x + this.speed;
}
}
Héritage
class BouncingBloc extends AnimatedBloc {
constructor(elt, {speed = 3, at = 300 } = {} ) {
super(elt, {speed});
this.boundary = at;
}
update() {
super.update();
if (this.x >= this.boundary || this.x == 0) {
this.speed *= -1;
this.elt.classList.toggle("bouncing");
}
}
}