JSFiddle - React, Tailwind, and code Playground

by sllark

HTML

<canvas id="myCanvas" width="480" height="320"></canvas>

CSS

canvas {
    border: 1px solid #333;
}

JavaScript

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

var ball = {
	x:  canvas.width/7,
  y:  canvas.height/2,
  speed: 3,
  angle: 45 * (Math.PI / 180),
  radius: 10
}

function drawBall() {
    ctx.beginPath();
    ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI*2);
    ctx.fillStyle = "#0095DD";
    ctx.fill();
    ctx.closePath();
}

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    ball.x += ball.speed * Math.sin(ball.angle)
    ball.y += ball.speed * -Math.cos(ball.angle)

		// collide with top wall
		if (ball.y <= 0) {
    	ball.angle = 180 * (Math.PI / 180)
    }

		drawBall();
    window.requestAnimationFrame(draw);
}

draw();