JSFiddle - React, Tailwind, and code Playground
HTML
<!-- From http://annotated-code.maryrosecook.com/circles-bouncing-off-lines/index.html -->
<canvas id="circles-bouncing-off-lines" width="300" height="300"></canvas>
JavaScript
;(function(exports) {
// The top-level functions that run the simulation
// -----------------------------------------------
// **start()** creates the lines and circles and starts the simulation.
function start() {
// In index.html, there is a canvas tag that the game will be drawn in.
// Grab that canvas out of the DOM. From it, get the drawing
// context, an object that contains functions that allow drawing to the canvas.
var screen = document.getElementById('circles-bouncing-off-lines').getContext('2d');
// `world` holds the current state of the world.
var world = {
circles: [],
// Set up the five lines.
lines: [
makeLine({ x: 100, y: 100 }),
makeLine({ x: 200, y: 100 }),
makeLine({ x: 150, y: 150 }),
makeLine({ x: 100, y: 200 }),
makeLine({ x: 220, y: 200 }),
],
dimensions: { x: screen.canvas.width, y: screen.canvas.height },
// `timeLastCircleMade` is used in the periodic creation of new circles.
timeLastCircleMade: 0
};
// **tick()** is the main simulation tick function. It loops forever, running 60ish times a second.
function tick() {
// Update state of circles and lines.
update(world);
// Draw circles and lines.
draw(world, screen);
// Queue up the next call to tick with the browser.
requestAnimationFrame(tick);
};
// Run the first game tick. All future calls will be scheduled by
// `tick()` itself.
tick();
};
// Export `start()` so it can be run by index.html
exports.start = start;
// **update()** updates the state of the lines and circles.
function update(world) {
// Move and bounce the circles.
updateCircles(world)
// Create new circle if one hasn't been created for a while.
createNewCircleIfDue(world);
// Rotate the lines.
updateLines(world);
};
// **updateCircles()** moves and bounces the circles.
function...