JSFiddle - React, Tailwind, and code Playground
by Josh Pullen
HTML
<input type="range" min="0" max="100" value="0" />
CSS
canvas {
border: 1px solid black;
}
JavaScript
class Value {
constructor(value) {
this._value = value;
}
get value() {
return this._value;
}
}
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
document.body.append(canvas);
canvas.width = 640;
canvas.height = 480;
function line(x1, y1, x2, y2) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
let ax, ay, bx, by, cx, cy;
function update(t) {
const lerp = (start, end, time = t) => start + (end - start) * time;
ax = 150;
ay = 325;
bx = 490;
by = 325;
cx = lerp(200, 490);
cy = 175;
}
function render() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#ddd";
ctx.beginPath();
ctx.moveTo(ax, ay);
ctx.lineTo(bx, by);
ctx.lineTo(cx, cy);
ctx.lineTo(ax, ay);
ctx.fill();
ctx.lineWidth = 6;
ctx.strokeStyle = "#a903fc";
line(ax, ay, bx, by);
ctx.strokeStyle = "red";
line(bx, by, cx, cy);
ctx.strokeStyle = "blue";
line(cx, cy, ax, ay);
const pointRadius = 8;
ctx.fillStyle = "black";
ctx.beginPath();
ctx.arc(ax, ay, pointRadius, 0, 2 * Math.PI);
ctx.fill();
ctx.beginPath();
ctx.arc(bx, by, pointRadius, 0, 2 * Math.PI);
ctx.fill();
ctx.beginPath();
ctx.arc(cx, cy, pointRadius, 0, 2 * Math.PI);
ctx.fill();
ctx.fillStyle = "red";
ctx.font = "30px serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(
Math.round(Math.hypot(cx - bx, cy - by)),
(bx + cx) / 2 + 50,
(by + cy) / 2
);
}
update(0);
render();
document.querySelector("input")
.addEventListener("input", (event) => {
update(Number(event.target.value) / 100);
render();
});