SVG Boundary Detection 1
by fiddlerintheoffice
HTML
<button>Randomize</button>
<svg xmnls="http://www.w3.org/2000/svg">
<circle r="50" cx="200" cy="200" id="example2" />
<rect r="50" x="400" y="300" width="100" height="80" id="example3" />
<rect r="0" x="0" y="300" width="100" height="80" id="bound" />
<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;
}
circle#example2 {
fill: blue;
}
rect#example3 {
fill: green;
}
rect#bound {
stroke: red;
stroke-width:2px;
}
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, example2, example3]));
}
function findLimits(paths) {
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}
}
for (let i = 0; i < paths.length; i++) {
let path = paths[i];
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);
})
}