JSFiddle - React, Tailwind, and code Playground
by davehawkins
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Session Code</title>
<style>
body {
font-family: sans-serif;
background: linen;
}
.animation {
width: 30px;
height: 30px;
border-radius: 15px;
position: absolute;
}
.animation-canvas {
position: relative;
}
.Objs_info {
margin: 10px 0px 0px 0px;
width: 200px;
font-weight: 600;
}
#Obj_0 {
background-color: #ff0000;
}
#Obj_1 {
background-color: #00ff00;
}
#Obj_2 {
background-color: #0000ff;
}
</style>
</head>
<body onload="onLoad ()">
<div class="Objs_info">Object 0</div>
<div id="Obj_0_data"></div>
<div class="Objs_info">Object 1</div>
<div id="Obj_1_data"></div>
<div class="Objs_info">Object 2</div>
<div id="Obj_2_data"></div>
<div class="animation-canvas">
<div class="animation" id="Obj_0"></div>
<div class="animation" id="Obj_1"></div>
<div class="animation" id="Obj_2"></div>
</div>
<script src="animation.js"></script>
</body>
</html>
JavaScript
//---------------------------------------------------
const ViewportWidth = 550;
const ViewportHeight = 550;
let Objs = [];
let Pos = [];
let XPos = [0, 0, 0];
let XVec = [3, 5, 7];
let YPos = [0, 0, 0];
let YVec = [8, 6, 4];
function onLoad() {
Objs[0] = document.getElementById("Obj_0");
Objs[1] = document.getElementById("Obj_1");
Objs[2] = document.getElementById("Obj_2");
setInterval(Update, 100);
}
function Update() {
let Idx = 0;
while (Idx < 3) {
if (XPos[Idx] < 0 || XPos[Idx] > ViewportWidth) {
XVec[Idx] *= -1;
}
if (YPos[Idx] < 0 || YPos[Idx] > ViewportHeight) {
YVec[Idx] *= -1;
}
XPos[Idx] += XVec[Idx];
YPos[Idx] += YVec[Idx];
Objs[Idx].style.left = XPos[Idx] + "px";
Objs[Idx].style.top = YPos[Idx] + "px";
// I added a function in here in an attempt to separate the concerns slightly, and make it more readable?
ObjData();
Pos[0] = XPos[0];
Idx++;
}
while (Idx < 3) {
Idx++;
}
}
/*
I can see that i'm repeating myself here, and I know there must be a way to "clean up" this code so I don't repeat myself, but i'm struggling when it comes to writing it.
*/
function ObjData() {
document.getElementById("Obj_0_data").textContent =
"X Position: " +
XPos[0] +
"px" +
" Y Position: " +
YPos[0] +
"px" +
" X Vector: " +
XVec[0] +
" Y Vector: " +
YVec[0];
document.getElementById("Obj_1_data").textContent =
"X Position: " +
XPos[1] +
"px" +
" Y Position: " +
YPos[1] +
"px" +
" X Vector: " +
XVec[1] +
" Y Vector: " +
YVec[1];
document.getElementById("Obj_2_data").textContent =
"X Position: " +
XPos[2] +
"px" +
" Y Position: " +
YPos[2] +
"px" +
" X Vector: " +
XVec[2] +
" Y Vector: " +
YVec[2];
}