JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id='animation' width='600' height='600' style='background: #ccc'></canvas>
JavaScript
const data = [
{ "UserId": 38, "Connections":[39,40] },
{ "UserId": 39, "Connections":[40] },
{ "UserId": 40, "Connections":[] }
];
const canvas = document.getElementById('animation');
const ctx = canvas.getContext('2d');
const users = [];
data.forEach(user => {
users.push({
id: user.UserId,
connections: user.Connections,
width: 80,
height: 80,
x: Math.round(Math.random() * (canvas.width - 80)),
y: Math.round(Math.random() * (canvas.height - 80)),
dir: {
x: Math.random() > 0.5 ? 1 : -1,
y: Math.random() > 0.5 ? 1 : -1
}
});
});
function drawUsers () {
ctx.clearRect(0, 0, canvas.width, canvas.height);
users.forEach(user => {
ctx.beginPath();
ctx.rect(user.x, user.y, user.width, user.height);
ctx.strokeStyle = 'red';
ctx.stroke();
ctx.closePath();
user.connections.forEach(connection => {
const other = users.find(user => user.id === connection);
ctx.beginPath();
ctx.moveTo(user.x + (user.width / 2), user.y + (user.height / 2));
ctx.lineTo(other.x + (other.width / 2), other.y + (other.height / 2));
ctx.strokeStyle = 'black';
ctx.stroke();
ctx.closePath();
});
});
window.requestAnimationFrame(drawUsers);
}
function updateUsers () {
users.forEach(user => {
if (user.x <= 0) user.dir.x = 1;
if (user.x + user.width > canvas.width) user.dir.x = -1;
if (user.y <= 0) user.dir.y = 1;
if (user.y + user.height > canvas.height) user.dir.y = -1;
user.x += user.dir.x;
user.y += user.dir.y;
});
window.setTimeout(updateUsers, 1000 / 60);
}
drawUsers();
updateUsers();