JSFiddle - React, Tailwind, and code Playground
by DupontTD
HTML
<div id="move">
move</div>
<div id="repeat">repeat</div>
<div id="bouncing">bouncing</div>
<button id="anim">testAnim</button>
<button id="stop">Stop</button>
CSS
div {
padding: 10px;
}
#move {
position: absolute;
left: 120px;
top: 100px;
background: indianred;
color: white
}
#repeat {
position: absolute;
left: 50px;
top: 150px;
background: crimson;
color: white
}
#bouncing {
width : 100px;
height: 100px;
position: absolute;
left: 100px;
top: 200px;
background: blue;
color: white;
display : flex;
align-content: center;
justify-content: center;
align-items: center;
}
.bouncing{
font-size : 1em;
border-radius : 50%;
background-color: red;
}
JavaScript
class AnimatedBloc {
constructor(elt, {speed = 1} = {} ) {
this.elt = elt;
// initial CSS
this.initPosition( speed );
}
initPosition( speed ) {
//console.log("init");
if (this.elt) {
const {
left,
top
} = this.elt.getBoundingClientRect();
// mémorise pos de départ du 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;
}
}
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");
}
}
}
class RepeatBloc extends AnimatedBloc {
constructor(elt, {speed = 1, at = 300 } = {} ) {
super(elt, {speed});
this.boundary = at;
}
update() {
super.update();
this.x = this.x % this.boundary;
}
// calcul surface
}
let players = [
new AnimatedBloc(document.getElementById("move"),{speed :0.1}),
new RepeatBloc(document.getElementById("repeat")),
new BouncingBloc(document.getElementById("bouncing"), {at : 500,speed :3})
];
function updateEntities(dt) {
players.forEach(function(player) {
player.update(dt);
});
}
function update(dt) {
updateEntities(dt);
}
function renderEntities() {
players.forEach(function(player) {
player.render();
});
}
function render() {
renderEntities();
}
function main() {
let now = Date.now(),
dt = (now - lastTime) / 1000.0;
update(dt);
render();
lastTime = now;
requestId = window.requestAnimationFrame(main);
}
function init() {
lastTime = Date.now();
main();
}
let requestId =...