Skip to content

Instantly share code, notes, and snippets.

@z-------------
Created December 19, 2019 10:28
Show Gist options
  • Save z-------------/d6ee26c55f470214f166a7210a032a4d to your computer and use it in GitHub Desktop.
Save z-------------/d6ee26c55f470214f166a7210a032a4d to your computer and use it in GitHub Desktop.
.bar {
border: solid 1px rgba(0, 0, 0, 0.3);
}
class Bar {
constructor(canvas) {
this.segments = [];
this.canvas = canvas;
canvas.classList.add("bar");
this.width = canvas.width;
this.height = canvas.height;
this.ctx = canvas.getContext("2d");
}
display(segments) {
if (!segments) segments = this.segments;
let offset = 0;
this.ctx.clearRect(0, 0, this.width, this.height);
for (let segment of segments) {
const w = this.width * segment.size;
this.ctx.fillStyle = segment.color || "#000000";
this.ctx.fillRect(offset, 0, w, this.height);
offset += w;
}
}
step(segments, duration, start, t) {
const displaySegments = [];
for (let i = 0; i < this.segments.length; ++i) {
const a = this.segments[i].size;
const b = segments[i].size;
displaySegments.push({
label: this.segments[i].label,
size: Bar.lerp(a, b, (t - start) / duration),
color: this.segments[i].color,
});
}
this.display(displaySegments);
if (t - start < duration) {
window.requestAnimationFrame(() => {
this.step(segments, duration, start, Date.now());
});
}
}
animate(segments, duration) {
this.step(segments, duration, Date.now(), Date.now());
}
static lerp(a, b, t) {
return a + t * (b - a);
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>KMMP</title>
<script src="bar.js"></script>
<link rel="stylesheet" href="bar.css"/>
</head>
<body>
<h1>KMMP</h1>
<canvas id="canvas" width="720" height="70"></canvas>
<script src="main.js"></script>
</body>
</html>
const canvas = document.getElementById("canvas");
const bar = new Bar(canvas);
bar.segments.push({
label: "Crap",
size: 0.3,
color: "#C9171E",
});
bar.segments.push({
label: "Dem",
size: 0.5,
color: "#004ea1",
});
bar.segments.push({
label: "Peoples",
size: 0.2,
color: "#006241",
});
bar.display();
bar.animate([
{ size: 0.1 },
{ size: 0.5 },
{ size: 0.4 }
], 5000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment