JSFiddle - React, Tailwind, and code Playground
by Josh Pullen
CSS
canvas {
border: 1px solid black;
}
JavaScript
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
canvas.width = 640;
canvas.height = 480;
document.body.appendChild(canvas);
let ball = {
radius: 10,
position: {
x: canvas.width / 2,
y: canvas.height / 2
},
vel: {
x: 5,
y: 2
},
render(ctx) {
ctx.fillStyle = "black";
ctx.beginPath();
ctx.arc(this.position.x, this.position.y, this.radius, 0, 2 * Math.PI);
ctx.fill();
},
move(canvas) {
this.position.x += this.vel.x;
this.position.y += this.vel.y;
if (this.position.x > canvas.width - this.radius) {
this.position.x = canvas.width - this.radius;
this.vel.x *= -1;
}
if (this.position.x < this.radius) {
this.position.x = this.radius;
this.vel.x *= -1;
}
if (this.position.y > canvas.height - this.radius) {
this.position.y = canvas.height - this.radius;
this.vel.y *= -1;
}
if (this.position.y < this.radius) {
this.position.y = this.radius;
this.vel.y *= -1;
}
}
};
function render() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ball.render(ctx);
}
function update() {
ball.move(canvas);
}
function tick() {
update();
render();
requestAnimationFrame(tick);
}
tick();