Skip to content

Instantly share code, notes, and snippets.

@bddicken
Last active July 23, 2024 20:47
Show Gist options
  • Save bddicken/154089735956133170e314f02eefe85b to your computer and use it in GitHub Desktop.
Save bddicken/154089735956133170e314f02eefe85b to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div id="container"></div>
</body>
<script>
const data = [{id: 0, height: 450, color: 'rgb(200, 100, 100)'},
{id: 1, height: 200, color: 'rgb(100, 200, 100)'},
{id: 2, height: 300, color: 'rgb(100, 100, 200)'},
{id: 3, height: 350, color: 'rgb(100, 200, 200)'}];
const svg = d3.select("#container").append("svg")
.attr("width", '1000px').attr("height", '500px');
const getRandom = (max) => {
return Math.floor(Math.random()*max);
}
const getRandomColor = () => {
const r = getRandom(255);
const g = getRandom(255);
const b = getRandom(255);
let x = `rgb(${r}, ${g}, ${b})`;
return x;
}
const refreshData = () => {
for (let i = 0; i < data.length; i++) {
data[i].height = getRandom(450);
data[i].color = getRandomColor();
}
console.log(data)
draw();
}
const draw = () => {
svg.selectAll(".node")
.data(data, (d) => d.id)
.join(
(enter) => enter.append('rect')
.attr('class', 'node')
.attr('width', 50),
(update) => update
.transition().duration(250)
.attr('y', (d) => 450 - d.height + 10)
.attr('height', (d) => d.height)
.style('fill', (d) => d.color),
(exit) => exit.call((exit) => exit.remove())
)
.transition().duration(250)
.style('fill', (d) => d.color)
.attr('height', (d) => d.height)
.attr('x', (d) => d.id * 55 + 100)
.attr('y', (d) => 450 - d.height + 10);
}
setInterval(refreshData, 1000);
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment