JSFiddle - React, Tailwind, and code Playground
by Artem
JavaScript
'use strict';
const canvas = document.createElement('canvas');
const button = document.createElement('button');
button.innerText = 'accelerate';
const context = canvas.getContext('2d');
canvas.height = 240;
canvas.width = 320;
canvas.style.border = '1px solid red';
document.body.append(canvas);
document.body.append(button);
let x = 20, y = 20;
let w = 50, h = 50;
let directionX = 1;
let directionY = 1;
let nMax = 10;
let n = 0;
let bounce = false;
let animationFrame;
context.fillRect(x, y, w, h);
const update = () => {
let delta = bounce ? n : 0;
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillRect(x+=directionX * 2, y+= 2 * directionY - delta, w, h);
if (x + w > canvas.width) {
directionX = -directionX;
}
if (x < 0) {
directionX = -directionX;
}
if (y < 0) {
directionY = -directionY;
}
if (y + h === canvas.height) {
directionY = -directionY;
}
n++;
if (n > nMax) {
n = 0;
bounce = false;
}
animationFrame = requestAnimationFrame(update);
};
button.onclick = () => {
bounce = true;
};
update();