SVG Boundary Detection 2
by fiddlerintheoffice
HTML
<button>Randomize</button>
<svg xmnls="http://www.w3.org/2000/svg">
<g id="svgg" transform="rotate(10)">
<circle r="50" cx="200" cy="200" id="example2" />
<rect x="400" y="300" width="100" height="80" id="example3" />
<path id="example" d="M10 10 C 20 20, 40 20, 50 10" />
</g>
<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" />
<rect x="0" y="0" width="0" height="0" id="bound" />
</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;
fill:transparent;
}
JavaScript
var example = document.getElementById("example");
var button = document.querySelector("button");
var svg = document.querySelector("svg");
var svgroup = document.querySelector("#svgg");
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]));
setTimeout(function() {svgroup.setAttribute('transform', 'rotate(0)')} ,5000);
}
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);
})
console.log(boundingPoints);
var bound = svg.getElementById('bound');
bound.setAttribute('x', boundingPoints['minX'].x);
bound.setAttribute('y', boundingPoints['minY'].y);
bound.setAttribute('width', boundingPoints['maxX'].x -...