123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
<script kotlin>
class Point(val id: Int, val x: Double, val y: Double)
var points by state(listOf(Point(1, 20.0, 78.0), Point(2, 65.0, 30.0), Point(3, 115.0, 58.0), Point(4, 175.0, 14.0)))
var nextId = 5
/** The line follows the points from left to right, whatever order they were added in. */
val line by derived { points.sortedBy { it.x }.joinToString(" ") { "${it.x},${it.y}" } }
</script>
<div class="demo">
<svg viewBox="0 0 200 100" role="img" aria-label="A line through {points.size} points"
@click={
val box = it.currentTarget.getBoundingClientRect()
points = points + Point(nextId++, (it.clientX - box.left) / box.width * 200, (it.clientY - box.top) / box.height * 100)
}>
<polyline points={line} />
@for (point in points, key = point.id) {
<circle cx={point.x} cy={point.y} r="4" @click={it.stopPropagation(); points = points - point} />
}
</svg>
<p>
<span>{points.size} points, click the plane to add one and a point to remove it.</span>
<button type="button" @click={points = emptyList()}>Clear</button>
</p>
</div>
<style>
svg {
display: block;
width: 100%;
border: 1px solid var(--rule);
border-radius: var(--radius);
background: radial-gradient(var(--grid) 1px, transparent 1px) 0 0 / 10px 10px, var(--paper);
cursor: crosshair;
}
polyline {
fill: none;
stroke: var(--accent);
stroke-width: 1.5;
stroke-linejoin: round;
}
circle {
fill: var(--paper);
stroke: var(--accent);
stroke-width: 1.5;
cursor: pointer;
transition: r 0.12s;
}
circle:hover {
r: 5.5;
}
p {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
margin: 0.6rem 0 0;
font: 0.78rem var(--mono);
color: var(--ink-muted);
}
button {
padding: 0.25rem 0.7rem;
border: 1px solid var(--rule-strong);
border-radius: var(--radius);
background: var(--paper-raised);
font: inherit;
cursor: pointer;
}
</style>