JSFiddle - React, Tailwind, and code Playground
HTML
<button>Randomize</button>
<svg xmnls="http://www.w3.org/2000/svg">
<path id="example" d="M10 10 C 20 20, 40 20, 50 10" />
<circle r="5" cx="0" cy="0" id="minX" />
<circle r="5" cx="0" cy="0" id="minY" />
<circle r="5" cx="0" cy="0" id="maxX" />
<circle r="5" cx="0" cy="0" id="maxY" />
</svg>
CSS
svg {
position: absolute;
height: 100%;
width: 100%;
display: block;
}
path {
fill: none;
stroke-width: 5;
stroke: black;
}
circle {
fill: red;
}
JavaScript
var example = document.getElementById("example");
var button = document.querySelector("button");
var svg = document.querySelector("svg");
button.addEventListener("click", randomize);
var dimensions= {
width: window.innerWidth,
height: window.innerHeight
}
randomize();
function randomize(){
var w = dimensions.width;
var h = dimensions.height;
var r = function(dim) {return Math.random() * dim};
example.setAttribute("d", "M" + r(w) + " " + r(h) + " C " + r(w) + " " + r(h) + ", " + r(w) + " " + r(h) + ", " + r(w) + " " + r(h))
drawLimits(findLimits(example));
}
function findLimits(path) {
var boundingPoints = {
minX: {x: dimensions.width, y: dimensions.height},
minY: {x: dimensions.width, y: dimensions.height},
maxX: {x: 0, y: 0},
maxY: {x: 0, y: 0}
}
var l = path.getTotalLength();
for (var p = 0; p < l; p++) {
var coords = path.getPointAtLength(p);
if (coords.x < boundingPoints.minX.x) boundingPoints.minX = coords;
if (coords.y < boundingPoints.minY.y) boundingPoints.minY = coords;
if (coords.x > boundingPoints.maxX.x) boundingPoints.maxX = coords;
if (coords.y > boundingPoints.maxY.y) boundingPoints.maxY = coords;
}
return boundingPoints
}
function drawLimits(boundingPoints){
["minX", "minY", "maxX", "maxY"].forEach(function(point){
var circle = svg.getElementById(point);
console.log(circle)
circle.setAttribute("cx", boundingPoints[point].x);
circle.setAttribute("cy", boundingPoints[point].y);
})
}