Apply updated co-ordinates from parent rotation to children - javascript

In the code below, I am rotating a selection box (parent) with two children in SVG.
It works fine, however, when the parent (selection box) is removed, the children go back to their original (pre-rotation) co-ordinates.
How can I apply the updated co-ordinates on the children once the parent is removed. I specifically need to maintain the new position of the children in X,Y co-oridinates, i.e. the rotate should be converted to translate, r.g. transform = translate (X , Y) . I only need New x,y for children so that i can 'translate' them to new location.
here is the fiddle link http://jsfiddle.net/rehankhalid/QK8L8/6/
HTML CODE:-
<button data-action="rotate" onclick="rotateMainRect()">Rotate +5 Angle</button>
<button data-action="rotate" onclick="removeRectRotation()">Remove Selection</button>
<br/>
<svg id="mainSvg" xmlns="http://www.w3.org/2000/svg" version="1.1" width="600" height="500">
<g id="selectedRect">
<rect id="rectangle" x="135" y="135" width="110" height="35" stroke="red" stroke-width="2" fill="grey" opacity="0.4" />
<g id="button_1" transform="translate(0,0)">
<circle cx="150" cy="150" r="5" stroke="grey" stroke-width="1" fill="none" />
</g>
<g id="button_2" transform="translate(0,0)">
<circle cx="230" cy="150" r="5" stroke="grey" stroke-width="1" fill="none" />
</g>
</g>
</svg>
JAVASCRIPT CODE
var angle_incr = 5;
var angle = 0;
function rotateMainRect() {
var selectedRect = document.getElementById('selectedRect');
var rectangle = document.getElementById('rectangle');
var x = rectangle.getAttribute('x');
if (x != 0) {
var centxy = calculateCenterXY(selectedRect);
angle += angle_incr;
selectedRect.setAttributeNS(null, 'transform', 'rotate(' + angle + ',' + centxy.x + ',' + centxy.y + ')');
} else {
rectangle.setAttribute('x', '135');
rectangle.setAttribute('y', '135');
rectangle.setAttribute('width', '110');
rectangle.setAttribute('height', '35');
}
}
function calculateCenterXY(node) {
var x = node.getBBox().x + (node.getBBox().width / 2);
var y = node.getBBox().y + (node.getBBox().height / 2);
var xy_co = {
x: x,
y: y
};
return xy_co;
}
function removeRectRotation() {
var selectedRect = document.getElementById('selectedRect');
selectedRect.setAttributeNS(null, 'transform', '');
var rectangle = document.getElementById('rectangle');
rectangle.setAttribute('x', '0');
rectangle.setAttribute('y', '0');
rectangle.setAttribute('width', '0');
rectangle.setAttribute('height', '0');
angle = 0;
}
- What i Want:-
First Rotate the selection rectangle to some angle, and then press 'Remove selection'. After Removing the selection, Childrens must be placed at the New postion. (which now, move back to the original position)

If you are asking if you can read the absolute positions of the two transformed circles directly using JS, then the answer is no.
You will need to calculate their positions yourself using a bit of trigonometry.

Related

D3 SVG Move zoom to rect inside <g> having different angle

I have <svg> with background images and different rectangle on that svg that are in proper position.
My rectangles are grouped by <g> with translation values and each rectangle has specific rotation values. Now I want my SVG to focus (show in center of page) on specific rectangle without disturbing background image and svg translate there.. Main issue is that these rectangles have different angles too.
So translate is not working properly....
SVG is like as below.
Can anyone provide me with guidelines?
<svg width="4500" height="3610" style="background: url("/images/001.jpg") no-repeat;">
<g id="228" transform="translate(2001,620)rotate(216) translate(0 -216)">
<g>
<rect x="0" y="0" height="72" width="36" stroke="black" style="fill: transparent;">
</rect><text x="0" y="36" text-anchor="start" style="fill: black;">228</text>
</g>
<g>
<rect x="36" y="0" height="72" width="36" stroke="black" style="fill: transparent;">
</rect><text x="36" y="36" text-anchor="start" style="fill: black;">229</text>
</g>
</g>
</svg>
This should be easier in SVG, and it might be, but here's my solution:
First, we need to get the bounding box of the rectangle we want to zoom to in it's coordinate space:
// Bounds in local coordinates space:
var bounds = rectElement.getBBox();
Second we get four corners out of this bounding box:
// Corners of rect in local coordinate space:
var corners = [
{x: bounds.x,y: bounds.y},
{x: bounds.x + bounds.width, y: bounds.y},
{x: bounds.x + bounds.width, y: bounds.y + bounds.height },
{x: bounds.x, y: bounds.y + bounds.height }
];
Third, we get the transformation matrix between the rectangle and the SVG:
// relevant transform:
var t = rectElement.getCTM();
Now, we can convert the corners we have to global SVG units:
// Convert the points to global SVG coordainte space:
for(var i = 0; i < corners.length; i++) {
var point = svg.node().createSVGPoint();
point.x = corners[i].x;
point.y = corners[i].y;
corners[i] = point.matrixTransform(t);
}
Ok, at this point we have the corners of the rotated rectangle in usable coordinates. We want to find the width and the height of these coordinates:
// get extents for x,y in global SVG space:
var x = d3.extent(corners, function(d) { return d.x; });
var y = d3.extent(corners, function(d) { return d.y; });
var w = x[1] - x[0];
var h = y[1] - y[0];
This gives us the rotated width and height, which we can now use to scale the SVG:. I'm using a small margin in my scaling function here (10% margin on each side):
// For getting scale factor:
var scale = function(elementWidth,elementHeight,SVGWidth,SVGHeight) {
return Math.min(SVGWidth/elementWidth*0.8,SVGHeight/elementHeight*0.8);
}
Which I use as so:
var k = scale(w,h,SVGwidth,SVGheight);
At this point I can zoom to the rectangle with a translate of -x[0]*k, -y[0]*k and a scale of k. However, this will result in the shape in the top left corner of the SVG, I want to account for the margin and whatever of rectangle width/height is smaller relative to SVG width/height. For this I calculate an offset for each of x, y:
// Offset to center feature:
var ox = (SVGwidth - w*k)/2;
var oy = (SVGheight- h*k)/2;
And now I can create my transform to center a given rectangle in the SVG:
var newTransform = "translate("+[-x[0]*k+ox,-y[0]*k+oy]+")scale("+k+")";
These snippets use a parent g to hold everything in the SVG, this makes it easier to manage the transforms. Also, this g has it's transform wiped when zooming to a rectangle because we don't want the relative transform from the current zoom state/transform, but one to the original zoom state/transform, otherwise we'll see odd behavior.
Here's an example with a zoom behavior allowing you to zoom/pan manually, but with the option to click to zoom to a rectangle:
var svg = d3.select("svg");
var contents = svg.html();
svg.selectAll("*").remove();
var g = svg.append("g")
.attr("transform", "translate(0,0)scale(1)")
.html(contents);
var SVGwidth = 400;
var SVGheight = 180;
// For getting scale factor:
var scale = function(elementWidth,elementHeight,SVGWidth,SVGHeight) {
return Math.min(SVGWidth/elementWidth*0.8,SVGHeight/elementHeight*0.8);
}
var zoom = d3.zoom()
.on("zoom", function(d) {
g.attr("transform",d3.event.transform);
})
svg.call(zoom);
function zoomToRect(rect) {
// Bounds in local coordinates space:
var bounds = rect.getBBox();
// Corners of rect in local coordinate space:
var corners = [
{x: bounds.x,y: bounds.y},
{x: bounds.x + bounds.width, y: bounds.y},
{x: bounds.x + bounds.width, y: bounds.y + bounds.height },
{x: bounds.x, y: bounds.y + bounds.height }
];
// Reset transform:
g.attr("transform","");
// relevant transform:
var t = rect.getCTM();
// Convert the points to global SVG coordainte space:
for(var i = 0; i < corners.length; i++) {
var point = svg.node().createSVGPoint();
point.x = corners[i].x;
point.y = corners[i].y;
corners[i] = point.matrixTransform(t);
}
// get extents for x,y in global SVG space:
var x = d3.extent(corners, function(d) { return d.x; });
var y = d3.extent(corners, function(d) { return d.y; });
var w = x[1] - x[0];
var h = y[1] - y[0];
var k = scale(w,h,SVGwidth,SVGheight);
// Offset to center feature:
var ox = (SVGwidth - w*k)/2;
var oy = (SVGheight- h*k)/2;
var newTransform = d3.zoomIdentity
.translate(-x[0]*k+ox,-y[0]*k+oy)
.scale(k);
svg.call(zoom.transform,newTransform);
}
d3.select("button").on("click", function() { zoomToRect(d3.select("rect").node()) });
svg {
border: 1px dotted black;
}
div {
position: absolute;
top: 0;
left: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width="400" height="180" style="background: url("/images/001.jpg") no-repeat;">
<g id="228" transform="translate(2001,620)rotate(216) translate(0 -216)">
<g>
<rect x="0" y="0" height="72" width="36" stroke="black" style="fill: transparent;"></rect>
<text x="0" y="36" text-anchor="start" style="fill: black;">228</text>
</g>
<g>
<rect x="36" y="0" height="72" width="36" stroke="black" style="fill: transparent;">
</rect><text x="36" y="36" text-anchor="start" style="fill: black;">229</text>
</g>
</g>
<g id="228" transform="translate(1801,550)rotate(65) translate(0 0)">
<g>
<rect x="0" y="0" height="100" width="20" stroke="black" style="fill: transparent;"></rect>
<text x="0" y="36" text-anchor="start" style="fill: black;">454</text>
</g>
<g>
<rect x="36" y="0" height="20" width="100" stroke="black" style="fill: transparent;">
</rect><text x="36" y="36" text-anchor="start" style="fill: black;">455</text>
</g>
</g>
</svg>
<div><button>Zoom to 228</button></div>
Here's a snippet that is just zooming around without a zoom behavior, cycling between four rectangles using your SVG plus two bonus rectangles:
var svg = d3.select("svg");
var contents = svg.html();
svg.selectAll("*").remove();
var g = svg.append("g")
.attr("transform", "translate(0,0)scale(1)")
.html(contents);
var SVGwidth = 400;
var SVGheight = 180;
// For getting scale factor:
var scale = function(elementWidth,elementHeight,SVGWidth,SVGHeight) {
return Math.min(SVGWidth/elementWidth*0.8,SVGHeight/elementHeight*0.8);
}
var current = 0;
function transition() {
g.selectAll("rect").each(function(_,i,n) {
if(i != current) return;
// Bounds in local coordinates space:
var bounds = n[i].getBBox();
// Corners of rect in local coordinate space:
var corners = [
{x: bounds.x,y: bounds.y},
{x: bounds.x + bounds.width, y: bounds.y},
{x: bounds.x + bounds.width, y: bounds.y + bounds.height },
{x: bounds.x, y: bounds.y + bounds.height }
];
// Hold original transform:
var oldTransform = g.attr("transform");
// Reset transform:
g.attr("transform","");
// relevant transform:
var t = n[i].getCTM();
// Convert the points to global SVG coordainte space:
for(var i = 0; i < corners.length; i++) {
var point = svg.node().createSVGPoint();
point.x = corners[i].x;
point.y = corners[i].y;
corners[i] = point.matrixTransform(t);
}
// get extents for x,y in global SVG space:
var x = d3.extent(corners, function(d) { return d.x; });
var y = d3.extent(corners, function(d) { return d.y; });
var w = x[1] - x[0];
var h = y[1] - y[0];
var k = scale(w,h,SVGwidth,SVGheight);
// Offset to center feature:
var ox = (SVGwidth - w*k)/2;
var oy = (SVGheight- h*k)/2;
var newTransform = "translate("+[-x[0]*k+ox,-y[0]*k+oy]+")scale("+k+")"
g.attr("transform",oldTransform)
.transition()
.on("start", function() {
d3.select(n[current]).style("fill","orange");
})
.duration(2000)
.attr("transform",newTransform)
.on("end", function() {
d3.select(n[current]).style("fill","none");
current++;
current = current%g.selectAll("rect").size();
transition();
})
})
}
transition();
svg {
border: 1px dotted black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width="400" height="180" style="background: url("/images/001.jpg") no-repeat;">
<g id="228" transform="translate(2001,620)rotate(216) translate(0 -216)">
<g>
<rect x="0" y="0" height="72" width="36" stroke="black" style="fill: transparent;"></rect>
<text x="0" y="36" text-anchor="start" style="fill: black;">228</text>
</g>
<g>
<rect x="36" y="0" height="72" width="36" stroke="black" style="fill: transparent;">
</rect><text x="36" y="36" text-anchor="start" style="fill: black;">229</text>
</g>
</g>
<g id="228" transform="translate(1801,550)rotate(65) translate(0 0)">
<g>
<rect x="0" y="0" height="100" width="20" stroke="black" style="fill: transparent;"></rect>
<text x="0" y="36" text-anchor="start" style="fill: black;">454</text>
</g>
<g>
<rect x="36" y="0" height="20" width="100" stroke="black" style="fill: transparent;">
</rect><text x="36" y="36" text-anchor="start" style="fill: black;">455</text>
</g>
</g>
</svg>

Fit SVG transformed element into the rect bounds with JavaScript

I am struggling with an issue to fit pragmatically transformed SVG element into the given rect bounds.
Destination rect is given and not transformed.
Input rect has any type of transformations.
Input rect can be a child of any transformed groups.
Transformations should be applied only to the input rect.
This question is only about the JavaScript element transformations.
It's an easy task when the element has only transformations by itself:
In this case proportion between the destination and input getBoundingClientRect (bounding rect in screen coordinates) is equals to a proper scaling factor.
But it's not working when parent elements are also transformed:
var inputElement = document.getElementById("input");
var destinationElement = document.getElementById("destination");
var inputBB = inputElement.getBoundingClientRect();
var outputBB = destinationElement.getBoundingClientRect();
var scaleX = outputBB.width / inputBB.width;
var scaleY = outputBB.height / inputBB.height;
// get offsets between figure center and destination rect center:
var offsetX = outputBB.x + outputBB.width / 2 - (inputBB.x + inputBB.width / 2);
var offsetY =
outputBB.y + outputBB.height / 2 - (inputBB.y + inputBB.height / 2);
// get current figure transformation
let currentMatrix = (
inputElement.transform.baseVal.consolidate() ||
inputElement.ownerSVGElement.createSVGTransform()
).matrix;
// Get center of figure in element coordinates:
const inputBBox = inputElement.getBBox();
const centerTransform = inputElement.ownerSVGElement.createSVGPoint();
centerTransform.x = inputBBox.x + inputBBox.width / 2;
centerTransform.y = inputBBox.y + inputBBox.height / 2;
// create scale matrix:
const svgTransform = inputElement.ownerSVGElement.createSVGTransform();
svgTransform.setScale(scaleX, scaleY);
let scalingMatrix = inputElement.ownerSVGElement
.createSVGMatrix()
// move the figure to the center of the destination rect.
.translate(offsetX, offsetY)
// Apply current matrix, so old transformations are not lost
.multiply(currentMatrix)
.translate(centerTransform.x, centerTransform.y)
// multiply is used instead of the scale method while for some reasons matrix scale is giving proportional scaling...
// From a transforms proper matrix is generated.
.multiply(svgTransform.matrix)
.translate(-centerTransform.x, -centerTransform.y);
// Apply new created matrix to element back:
const newTransform = inputElement.ownerSVGElement.createSVGTransform();
newTransform.setMatrix(scalingMatrix);
inputElement.transform.baseVal.initialize(newTransform);
var bboundsTest= document.getElementById("bboundsTest");
const resultBBounds = inputElement.getBoundingClientRect();
bboundsTest.setAttribute('x', resultBBounds .x);
bboundsTest.setAttribute('y', resultBBounds .y);
bboundsTest.setAttribute('width', resultBBounds .width);
bboundsTest.setAttribute('height', resultBBounds .height);
document.getElementById('test2').innerHTML = 'expected: 100x100 . Results: ' + resultBBounds.width + 'x' + resultBBounds.height
<svg
version="1.2"
viewBox="0 0 480 150"
width="480"
height="150"
xmlns="http://www.w3.org/2000/svg"
>
<g transform="skewX(10) translate(95,1) rotate(30)">
<g transform="skewX(30) translate(-3,3) rotate(30)">
<g transform="skewX(10) translate(-3,4) rotate(10)">
<rect
id="input"
transform="translate(95,76.5) skewX(25) translate(50,50) scale(1.5) translate(-50,-50) translate(0,0) rotate(45)"
width="30"
height="30"
fill="red"
/>
</g>
</g>
</g>
<rect
id="destination"
x="20"
y="20"
width="100"
height="100"
fill="transparent"
stroke="blue"
/>
<rect
id="bboundsTest"
x="20"
y="20"
width="100"
height="100"
fill="transparent"
stroke="black"
/>
</svg>
<div id="test2"></div>
Any ideas on how to take parent transformations into the count to find proper scaling factors?
Thanks in advance for the ideas!
The given answer from Dipen Shah is focused on applying transformations to the parent element and this is also an option, but my goal is transforming the element to the destination rect bounds.
As you have discovered, this is a tricky problem. It's even trickier than you think (see later).
You have rectangles in two different corrdinate spaces. One of them is transformed. So you are trying to map one transformed rectangle to another, possibly transformed, rectangle. Since they are transformed, one or both of those rectangles is (probably) no longer a rectangle.
Since your requirement is to transform the "input" to the "destination", the way to get your head around the problem is to switch your coordinate space to the point of view of the "input" rect. What does the "destination" look like from the point of view of "input"? To see, we need to transform "destination" with the inverse of the transform that "input" has.
What the destination looks like to the <rect id="input" transform=""/>
<svg
version="1.2"
viewBox="-50 -50 160 260"
height="500"
xmlns="http://www.w3.org/2000/svg"
>
<rect
id="input"
transform="translate(95,76.5) skewX(25) translate(50,50) scale(1.5) translate(-50,-50) translate(0,0) rotate(45)"
width="30"
height="30"
fill="red"
/>
<g transform="rotate(-10) translate(3,-4) skewX(-10)">
<g transform="rotate(-30) translate(3,-3) skewX(-30)">
<g transform="rotate(-30) translate(-95,-1) skewX(-10)">
<rect
id="destination"
x="20"
y="20"
width="100"
height="100"
fill="transparent"
stroke="blue"
/>
</g>
</g>
</g>
What the destination looks like to the <rect id="input"/>
<svg
version="1.2"
viewBox="-80 -70 120 230"
height="500"
xmlns="http://www.w3.org/2000/svg"
>
<rect
id="input"
width="30"
height="30"
fill="red"
/>
<g transform="rotate(-45) translate(0,0) translate(50,50) scale(0.67) translate(-50,-50) skewX(-25) translate(-95,-76.5)">
<g transform="rotate(-10) translate(3,-4) skewX(-10)">
<g transform="rotate(-30) translate(3,-3) skewX(-30)">
<g transform="rotate(-30) translate(-95,-1) skewX(-10)">
<rect
id="destination"
x="20"
y="20"
width="100"
height="100"
fill="transparent"
stroke="blue"
/>
</g>
</g>
</g>
</g>
So, you can see why it's so tricky now. We either have to find the transform that maps a parallelogram to another parallelogram, or a rectangle to a parallelogram. Obviously we'll want to choose the latter. You'd expect it to be the simpler of the two options.
We are also helped because we can assume that the transformations are affine. Straight lines stay straight, and parallel lines stay parallel.
So our task is to scale up our rectangle, so that it neatly fits inside our destination parallelogram. Also, because the parallelogram has 180° rotational symmetry, we know that the centre of our fitted rectangle will coincide with the centre of the parallelogram.
So, let's imagine the "input" rectangle is sitting at the centre of the "destination" parallelogram, then shoot imaginary rays out of the rectangle until they hit the sides of the parallelogram. Whichever ray hits the destination parallelogram first, gives us the scale we should apply to the rectangle to make it fit.
.ray {
stroke: lightgrey;
stroke-dasharray: 2 2;
}
<svg
version="1.2"
viewBox="0 0 120 230"
height="500"
xmlns="http://www.w3.org/2000/svg"
>
<g transform="translate(47.1,101.2)"><!-- positioning conveniently for our figure -->
<!-- scaling rays -->
<line class="ray" x1="-100" y1="0" x2="100" y2="0"/>
<line class="ray" x1="-100" y1="30" x2="100" y2="30"/>
<line class="ray" x1="0" y1="-100" x2="0" y2="100"/>
<line class="ray" x1="30" y1="-100" x2="30" y2="100"/>
<rect
id="input"
width="30"
height="30"
fill="red"
/>
</g>
<g transform="translate(80,70)"><!-- positioning conveniently for our figure -->
<g transform="rotate(-45) translate(0,0) translate(50,50) scale(0.67) translate(-50,-50) skewX(-25) translate(-95,-76.5)">
<g transform="rotate(-10) translate(3,-4) skewX(-10)">
<g transform="rotate(-30) translate(3,-3) skewX(-30)">
<g transform="rotate(-30) translate(-95,-1) skewX(-10)">
<rect
id="destination"
x="20"
y="20"
width="100"
height="100"
fill="transparent"
stroke="blue"
/>
</g>
</g>
</g>
</g>
</g>
var inputElement = document.getElementById("input");
var destinationElement = document.getElementById("destination");
var svg = inputElement.ownerSVGElement;
// Get the four corner points of rect "input"
var inX = inputElement.x.baseVal.value;
var inY = inputElement.y.baseVal.value;
var inW = inputElement.width.baseVal.value;
var inH = inputElement.height.baseVal.value;
// Get the four corner points of rect "destination"
var destX = destinationElement.x.baseVal.value;
var destY = destinationElement.y.baseVal.value;
var destW = destinationElement.width.baseVal.value;
var destH = destinationElement.height.baseVal.value;
var destPoints = [
createPoint(svg, destX, destY),
createPoint(svg, destX + destW, destY),
createPoint(svg, destX + destW, destY + destH),
createPoint(svg, destX, destY + destH)
];
// Get total transform applied to input rect
var el = inputElement;
var totalMatrix = el.transform.baseVal.consolidate().matrix;
// Step up ancestor tree till we get to the element before the root SVG element
while (el.parentElement.ownerSVGElement != null) {
el = el.parentElement;
if (el.transform) {
totalMatrix = el.transform.baseVal.consolidate().matrix.multiply( totalMatrix );
}
}
//console.log("totalMatrix = ",totalMatrix);
// Transform the four "destination" rect corner points by the inverse of the totalMatrix
// We will then have the corner points in the same coordinate space as the "input" rect
for (var i=0; i<4; i++) {
destPoints[i] = destPoints[i].matrixTransform(totalMatrix.inverse());
}
//console.log("transformed destPoints=",destPoints);
// Find the equation for the rays that start at the centre of the "input" rect & "destination" parallelogram
// and pass through the corner points of the "input" rect.
var destMinX = Math.min(destPoints[0].x, destPoints[1].x, destPoints[2].x, destPoints[3].x);
var destMaxX = Math.max(destPoints[0].x, destPoints[1].x, destPoints[2].x, destPoints[3].x);
var destMinY = Math.min(destPoints[0].y, destPoints[1].y, destPoints[2].y, destPoints[3].y);
var destMaxY = Math.max(destPoints[0].y, destPoints[1].y, destPoints[2].y, destPoints[3].y);
var destCentreX = (destMinX + destMaxX) / 2;
var destCentreY = (destMinY + destMaxY) / 2;
// Find the scale in the X direction by shooting rays horizontally from the top and bottom of the "input" rect
var scale1 = findDistanceToDestination(destCentreX, destCentreY - inH/2, inW/2, 0, // line equation of ray line 1
destPoints);
var scale2 = findDistanceToDestination(destCentreX, destCentreY + inH/2, inW/2, 0, // line equation of ray line 2
destPoints);
var scaleX = Math.min(scale1, scale2);
// Find the scale in the Y direction by shooting rays vertically from the left and right of the "input" rect
scale1 = findDistanceToDestination(destCentreX - inW/2, destCentreY, 0, inH/2, // line equation of ray line 1
destPoints);
scale2 = findDistanceToDestination(destCentreX + inW/2, destCentreY, 0, inH/2, // line equation of ray line 2
destPoints);
var scaleY = Math.min(scale1, scale2);
// Now we can position and scale the "input" element to fit the "destination" rect
inputElement.transform.baseVal.appendItem( makeTranslate(svg, destCentreX, destCentreY));
inputElement.transform.baseVal.appendItem( makeScale(svg, scaleX, scaleY));
inputElement.transform.baseVal.appendItem( makeTranslate(svg, -(inX + inW)/2, -(inY + inH)/2));
function createPoint(svg, x, y)
{
var pt = svg.createSVGPoint();
pt.x = x;
pt.y = y;
return pt;
}
function makeTranslate(svg, x, y)
{
var t = svg.createSVGTransform();
t.setTranslate(x, y);
return t;
}
function makeScale(svg, sx, sy)
{
var t = svg.createSVGTransform();
t.setScale(sx, sy);
return t;
}
function findDistanceToDestination(centreX, centreY, rayX, rayY, // line equation of ray
destPoints) // parallelogram points
{
// Test ray against each side of the dest parallelogram
for (var i=0; i<4; i++) {
var from = destPoints[i];
var to = destPoints[(i + 1) % 4];
var dx = to.x - from.x;
var dy = to.y - from.y;
var k = intersection(centreX, centreY, rayX, rayY, // line equation of ray
from.x, from.y, dx, dy); // line equation of parallogram side
if (k >= 0 && k <= 1) {
// Ray intersected with this side
var interceptX = from.x + k * dx;
var interceptY = from.y + k * dy;
var distanceX = interceptX - centreX;
var distanceY = interceptY - centreY;
if (rayX != 0)
return Math.abs(distanceX / rayX);
else if (rayY != 0)
return Math.abs(distanceY / rayY);
else
return 0; // How to handle case where "input" rect has zero width or height?
}
}
throw 'Should have intersected one of the sides!'; // Shouldn't happen
}
// Returns the position along the 'side' line, that the ray hits.
// If it intersects the line, thre return value will be between 0 and 1.
function intersection(rayX, rayY, rayDX, rayDY,
sideX, sideY, sideDX, sideDY)
{
// We want to find where:
// rayXY + t * rayDXDY = sideXY + k * sideDXDY
// Returning k.
// See: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection
var den = -rayDX * -sideDY - -rayDY * -sideDX;
return (den != 0) ? - (-rayDX * (rayY-sideY) - -rayDY * (rayX-sideX)) / den
: -9999; // Lines don't intersect. Return a value outside range 0..1.
}
<svg
version="1.2"
viewBox="0 0 480 150"
width="480"
height="150"
xmlns="http://www.w3.org/2000/svg"
>
<g transform="skewX(10) translate(95,1) rotate(30)">
<g transform="skewX(30) translate(-3,3) rotate(30)">
<g transform="skewX(10) translate(-3,4) rotate(10)">
<rect
id="input"
transform="translate(95,76.5) skewX(25) translate(50,50) scale(1.5) translate(-50,-50) translate(0,0) rotate(45)"
width="30"
height="30"
fill="red"
/>
</g>
</g>
</g>
<rect
id="destination"
x="20"
y="20"
width="100"
height="100"
fill="transparent"
stroke="blue"
/>
</svg>
<div id="test2"></div>
We got close, but we're a little oversized. What happened?
If we go back to looking at it in "input" rect space, like before, we can see the problem better.
<svg width="500" height="500" viewBox="-40 -40 50 180">
<polygon points="-38.5008, 79.5321,
-32.7704, -35.2044,
3.5896, 12.3685,
-2.1406, 127.1050"
fill="none"
stroke="blue"
stroke-width="0.5"/>
<!-- input -->
<rect x="-32.4555" y="30.9503" width="30" height="30"
fill="red"/>
<!-- centre of dest -->
<circle cx="-17.4555" cy="45.9503" r="1"/>
<!-- intercepts X -->
<circle cx="-36.0744" cy="30.9503" r="1" fill="green"/>
<circle cx="-37.5727" cy="60.9503" r="1" fill="green"/>
<!-- intercepts Y -->
<circle cx="-32.4555" cy="-34.7923" r="1" fill="green"/>
<circle cx="-2.4555" cy="4.4590" r="1" fill="green"/>
<!-- scaled input -->
<rect x="-32.4555" y="30.9503" width="30" height="30"
fill="red" fill-opacity="0.2"
transform="translate(-17.4556 45.9503) scale(1.24126 2.76608) translate(17.4556 -45.9503)"/>
</svg>
The green dots represent the intersection points we got from shooting the rays horizontally and vertically from our "input" rectangle. The faded red rectangle represents the "input" rectangle scaled up to touch our intercept points. It overflows our "destination" shape. Which is why our shape from the previous snippet overflows, also.
This is what I meant, at the very top, when I said it is trickier than you think. To make the "input" match the "destination", you have to tweak two inter-dependent X and Y scales. If you adjust the X scale to fit, it'll no long fit in the Y direction. And vice versa.
This is as far as I want to go. I've spent a couple of hours on this answer already.
Perhaps their's a mathematical solution for finding a rectangle that fits inside a
parallelogram and touches all four sides. But I don't really want to spend the time to
work it out. Sorry. :)
Perhaps you or someone else can take this further. You could also try an iterative
solution that nudges the X and Y scales iteratively until it gets close enough.
Finally, if you are prepared to accept the condition that you don't stretch the input both horizontally and vertically, and if you are okay with just scaling up (or down) the input to fit (ie keeping the aspect ratio the same), then that's a simpler thing to solve.
var inputElement = document.getElementById("input");
var destinationElement = document.getElementById("destination");
var svg = inputElement.ownerSVGElement;
// Get the four corner points of rect "input"
var inX = inputElement.x.baseVal.value;
var inY = inputElement.y.baseVal.value;
var inW = inputElement.width.baseVal.value;
var inH = inputElement.height.baseVal.value;
// Get the four corner points of rect "destination"
var destX = destinationElement.x.baseVal.value;
var destY = destinationElement.y.baseVal.value;
var destW = destinationElement.width.baseVal.value;
var destH = destinationElement.height.baseVal.value;
var destPoints = [
createPoint(svg, destX, destY),
createPoint(svg, destX + destW, destY),
createPoint(svg, destX + destW, destY + destH),
createPoint(svg, destX, destY + destH)
];
// Get total transform applied to input rect
var el = inputElement;
var totalMatrix = el.transform.baseVal.consolidate().matrix;
// Step up ancestor tree till we get to the element before the root SVG element
while (el.parentElement.ownerSVGElement != null) {
el = el.parentElement;
if (el.transform) {
totalMatrix = el.transform.baseVal.consolidate().matrix.multiply( totalMatrix );
}
}
//console.log("totalMatrix = ",totalMatrix);
// Transform the four "destination" rect corner points by the inverse of the totalMatrix
// We will then have the corner points in the same coordinate space as the "input" rect
for (var i=0; i<4; i++) {
destPoints[i] = destPoints[i].matrixTransform(totalMatrix.inverse());
}
//console.log("transformed destPoints=",destPoints);
// Find the equation for the rays that start at the centre of the "input" rect & "destination" parallelogram
// and pass through the corner points of the "input" rect.
var destMinX = Math.min(destPoints[0].x, destPoints[1].x, destPoints[2].x, destPoints[3].x);
var destMaxX = Math.max(destPoints[0].x, destPoints[1].x, destPoints[2].x, destPoints[3].x);
var destMinY = Math.min(destPoints[0].y, destPoints[1].y, destPoints[2].y, destPoints[3].y);
var destMaxY = Math.max(destPoints[0].y, destPoints[1].y, destPoints[2].y, destPoints[3].y);
var destCentreX = (destMinX + destMaxX) / 2;
var destCentreY = (destMinY + destMaxY) / 2;
// Shoot diagonal rays from the centre through two adjacent corners of the "input" rect.
// Whichever one hits the destination shape first, provides the scaling factor we need.
var scale1 = findDistanceToDestination(destCentreX, destCentreY, inW/2, inH/2, // line equation of ray line 1
destPoints);
var scale2 = findDistanceToDestination(destCentreX, destCentreY, -inW/2, inW/2, // line equation of ray line 2
destPoints);
var scale = Math.min(scale1, scale2);
// Now we can position and scale the "input" element to fit the "destination" rect
inputElement.transform.baseVal.appendItem( makeTranslate(svg, destCentreX, destCentreY));
inputElement.transform.baseVal.appendItem( makeScale(svg, scale, scale));
inputElement.transform.baseVal.appendItem( makeTranslate(svg, -(inX + inW)/2, -(inY + inH)/2));
function createPoint(svg, x, y)
{
var pt = svg.createSVGPoint();
pt.x = x;
pt.y = y;
return pt;
}
function makeTranslate(svg, x, y)
{
var t = svg.createSVGTransform();
t.setTranslate(x, y);
return t;
}
function makeScale(svg, sx, sy)
{
var t = svg.createSVGTransform();
t.setScale(sx, sy);
return t;
}
function findDistanceToDestination(centreX, centreY, rayX, rayY, // line equation of ray
destPoints) // parallelogram points
{
// Test ray against each side of the dest parallelogram
for (var i=0; i<4; i++) {
var from = destPoints[i];
var to = destPoints[(i + 1) % 4];
var dx = to.x - from.x;
var dy = to.y - from.y;
var k = intersection(centreX, centreY, rayX, rayY, // line equation of ray
from.x, from.y, dx, dy); // line equation of parallogram side
if (k >= 0 && k <= 1) {
// Ray intersected with this side
var interceptX = from.x + k * dx;
var interceptY = from.y + k * dy;
var distanceX = interceptX - centreX;
var distanceY = interceptY - centreY;
if (rayX != 0)
return Math.abs(distanceX / rayX);
else if (rayY != 0)
return Math.abs(distanceY / rayY);
else
return 0; // How to handle case where "input" rect has zero width or height?
}
}
throw 'Should have intersected one of the sides!'; // Shouldn't happen
}
// Returns the position along the 'side' line, that the ray hits.
// If it intersects the line, thre return value will be between 0 and 1.
function intersection(rayX, rayY, rayDX, rayDY,
sideX, sideY, sideDX, sideDY)
{
// We want to find where:
// rayXY + t * rayDXDY = sideXY + k * sideDXDY
// Returning k.
// See: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection
var den = -rayDX * -sideDY - -rayDY * -sideDX;
return (den != 0) ? - (-rayDX * (rayY-sideY) - -rayDY * (rayX-sideX)) / den
: -9999; // Lines don't intersect. Return a value outside range 0..1.
}
<svg
version="1.2"
viewBox="0 0 480 150"
width="480"
height="150"
xmlns="http://www.w3.org/2000/svg"
>
<g transform="skewX(10) translate(95,1) rotate(30)">
<g transform="skewX(30) translate(-3,3) rotate(30)">
<g transform="skewX(10) translate(-3,4) rotate(10)">
<rect
id="input"
transform="translate(95,76.5) skewX(25) translate(50,50) scale(1.5) translate(-50,-50) translate(0,0) rotate(45)"
width="30"
height="30"
fill="red"
/>
</g>
</g>
</g>
<rect
id="destination"
x="20"
y="20"
width="100"
height="100"
fill="transparent"
stroke="blue"
/>
</svg>
<div id="test2"></div>
Update:
I was able to fit source element to match target element. The way I was able to achieve that is by translating top most container of the source element relative to target element and scaling container based on size ratio between source and target elements.
function applyTransformations(source, sourceContainer, target, includeMagicScaleMargin) {
var sourceBB = source.getBoundingClientRect();
var inputBB = sourceContainer.getBoundingClientRect();
var outputBB = target.getBoundingClientRect();
var scaleX = (outputBB.width - (includeMagicScaleMargin ? 10 : 0)) / sourceBB.width;
var scaleY = (outputBB.height - (includeMagicScaleMargin ? 10 : 0)) / sourceBB.height;
// get offsets between figure center and destination rect center:
var offsetX = outputBB.x + outputBB.width / 2 - (inputBB.x + inputBB.width / 2);
var offsetY =
outputBB.y + outputBB.height / 2 - (inputBB.y + inputBB.height / 2);
// get current figure transformation
let currentMatrix = (
sourceContainer.transform.baseVal.consolidate() ||
sourceContainer.ownerSVGElement.createSVGTransform()
).matrix;
// Get center of figure in element coordinates:
const inputBBox = sourceContainer.getBBox();
const centerTransform = sourceContainer.ownerSVGElement.createSVGPoint();
centerTransform.x = inputBBox.x + inputBBox.width / 2;
centerTransform.y = inputBBox.y + inputBBox.height / 2;
// create scale matrix:
const svgTransform = sourceContainer.ownerSVGElement.createSVGTransform();
svgTransform.setScale(scaleX, scaleY);
let scalingMatrix = sourceContainer.ownerSVGElement
.createSVGMatrix()
// move the figure to the center of the destination rect.
.translate(offsetX, offsetY)
// Apply current matrix, so old transformations are not lost
.multiply(currentMatrix)
.translate(centerTransform.x, centerTransform.y)
// multiply is used instead of the scale method while for some reasons matrix scale is giving proportional scaling...
// From a transforms proper matrix is generated.
.multiply(svgTransform.matrix)
.translate(-centerTransform.x, -centerTransform.y);
// Apply new created matrix to element back:
const newTransform = sourceContainer.ownerSVGElement.createSVGTransform();
newTransform.setMatrix(scalingMatrix);
sourceContainer.transform.baseVal.initialize(newTransform);
}
function isDescendant(parent, child) {
var node = child.parentNode;
while (node != null) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
}
function transformSVG1() {
var destinationElem = document.getElementById("destination");
var inputElem = document.getElementById("input");
var inputContainerElem = inputElem;
while (inputContainerElem.parentNode != null) {
let candidateParent = inputContainerElem.parentNode;
if (isDescendant(candidateParent, destinationElem)) {
break;
}
inputContainerElem = candidateParent;
}
applyTransformations(inputElem, inputContainerElem, destinationElem);
}
function transformSVG2() {
var destinationElem = document.getElementById("destination2");
var inputElem = document.getElementById("input2");
var inputContainerElem = inputElem;
while (inputContainerElem.parentNode != null) {
let candidateParent = inputContainerElem.parentNode;
if (isDescendant(candidateParent, destinationElem)) {
break;
}
inputContainerElem = candidateParent;
}
applyTransformations(inputElem, inputContainerElem, destinationElem, true);
}
transformSVG1();
transformSVG2();
<svg version="1.2" viewBox="0 0 480 200" width="480" height="200" xmlns="http://www.w3.org/2000/svg">
<g>
<text x="0" y="20" font-size="20">No magic margins</text>
<g transform="skewX(10) translate(95,1) rotate(30)">
<g transform="skewX(30) translate(-3,3) rotate(30)">
<g transform="skewX(10) translate(-3,4) rotate(10)">
<rect id="input" transform="translate(95,76.5) skewX(25) translate(50,50) scale(1.5) translate(-50,-50) translate(0,0) rotate(45)" width="30" height="30" fill="red" />
</g>
</g>
</g>
<rect id="destination" x="40" y="40" width="100" height="100" fill="transparent" stroke="blue" />
</g>
</svg>
<svg version="1.2" viewBox="0 0 480 200" width="480" height="200" xmlns="http://www.w3.org/2000/svg">
<g>
<text x="0" y="20" font-size="20">Magic margins!</text>
<g transform="skewX(10) translate(95,1) rotate(30)">
<g transform="skewX(30) translate(-3,3) rotate(30)">
<g transform="skewX(10) translate(-3,4) rotate(10)">
<rect id="input2" transform="translate(95,76.5) skewX(25) translate(50,50) scale(1.5) translate(-50,-50) translate(0,0) rotate(45)" width="30" height="30" fill="red" />
</g>
</g>
</g>
<rect id="destination2" x="40" y="40" width="100" height="100" fill="transparent" stroke="blue" />
</g>
</svg>
Original answer:
I don't think this is an exact answer to what you are looking for but easier thing to do would be either:
Approach 1:
keep on applying same transformation as input element and its parent until common parent node is found.
function applyTransformations(source, target) {
var inputBB = source.getBoundingClientRect();
var outputBB = target.getBoundingClientRect();
var scaleX = outputBB.width / inputBB.width;
var scaleY = outputBB.height / inputBB.height;
// get offsets between figure center and destination rect center:
var offsetX = outputBB.x + outputBB.width / 2 - (inputBB.x + inputBB.width / 2);
var offsetY =
outputBB.y + outputBB.height / 2 - (inputBB.y + inputBB.height / 2);
// get current figure transformation
let currentMatrix = (
source.transform.baseVal.consolidate() ||
source.ownerSVGElement.createSVGTransform()
).matrix;
// Get center of figure in element coordinates:
const inputBBox = source.getBBox();
const centerTransform = source.ownerSVGElement.createSVGPoint();
centerTransform.x = inputBBox.x + inputBBox.width / 2;
centerTransform.y = inputBBox.y + inputBBox.height / 2;
// create scale matrix:
const svgTransform = source.ownerSVGElement.createSVGTransform();
svgTransform.setScale(scaleX, scaleY);
let scalingMatrix = source.ownerSVGElement
.createSVGMatrix()
// move the figure to the center of the destination rect.
.translate(offsetX, offsetY)
// Apply current matrix, so old transformations are not lost
.multiply(currentMatrix)
.translate(centerTransform.x, centerTransform.y)
// multiply is used instead of the scale method while for some reasons matrix scale is giving proportional scaling...
// From a transforms proper matrix is generated.
.multiply(svgTransform.matrix)
.translate(-centerTransform.x, -centerTransform.y);
// Apply new created matrix to element back:
const newTransform = source.ownerSVGElement.createSVGTransform();
newTransform.setMatrix(scalingMatrix);
source.transform.baseVal.initialize(newTransform);
}
function isDescendant(parent, child) {
var node = child.parentNode;
while (node != null) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
}
var destinationElement = document.getElementById("destination");
var inputElement = document.getElementById("input");
while (inputElement.parentNode != null) {
applyTransformations(inputElement, destinationElement);
let candidateParent = inputElement.parentNode;
if (isDescendant(candidateParent, destinationElement)) {
break;
}
inputElement = candidateParent;
}
// Test:
var bboundsTest= document.getElementById("bboundsTest");
const resultBBounds = document.getElementById("input").getBoundingClientRect();
bboundsTest.setAttribute('x', resultBBounds.x);
bboundsTest.setAttribute('y', resultBBounds.y);
bboundsTest.setAttribute('width', resultBBounds.width);
bboundsTest.setAttribute('height', resultBBounds.height);
<svg version="1.2" viewBox="0 0 480 240" width="480" height="240" xmlns="http://www.w3.org/2000/svg">
<g>
<g transform="skewX(10) translate(95,1) rotate(30)">
<g transform="skewX(30) translate(-3,3) rotate(30)">
<g transform="skewX(10) translate(-3,4) rotate(10)">
<rect
id="input"
transform="translate(95,76.5) skewX(25) translate(50,50) scale(1.5) translate(-50,-50) translate(0,0) rotate(45)"
width="30"
height="30"
fill="red"
/>
</g>
</g>
</g>
<rect
id="destination"
x="20"
y="20"
width="100"
height="100"
fill="transparent"
stroke="blue"
/>
<rect
id="bboundsTest"
fill="transparent"
stroke="black"
/>
</g>
</svg>
Approach 2:
Or find parent of input that is not parent of destination first and than apply same transformations as parent node.
function applyTransformations(source, target) {
var inputBB = source.getBoundingClientRect();
var outputBB = target.getBoundingClientRect();
var scaleX = outputBB.width / inputBB.width;
var scaleY = outputBB.height / inputBB.height;
// get offsets between figure center and destination rect center:
var offsetX = outputBB.x + outputBB.width / 2 - (inputBB.x + inputBB.width / 2);
var offsetY =
outputBB.y + outputBB.height / 2 - (inputBB.y + inputBB.height / 2);
// get current figure transformation
let currentMatrix = (
source.transform.baseVal.consolidate() ||
source.ownerSVGElement.createSVGTransform()
).matrix;
// Get center of figure in element coordinates:
const inputBBox = source.getBBox();
const centerTransform = source.ownerSVGElement.createSVGPoint();
centerTransform.x = inputBBox.x + inputBBox.width / 2;
centerTransform.y = inputBBox.y + inputBBox.height / 2;
// create scale matrix:
const svgTransform = source.ownerSVGElement.createSVGTransform();
svgTransform.setScale(scaleX, scaleY);
let scalingMatrix = source.ownerSVGElement
.createSVGMatrix()
// move the figure to the center of the destination rect.
.translate(offsetX, offsetY)
// Apply current matrix, so old transformations are not lost
.multiply(currentMatrix)
.translate(centerTransform.x, centerTransform.y)
// multiply is used instead of the scale method while for some reasons matrix scale is giving proportional scaling...
// From a transforms proper matrix is generated.
.multiply(svgTransform.matrix)
.translate(-centerTransform.x, -centerTransform.y);
// Apply new created matrix to element back:
const newTransform = source.ownerSVGElement.createSVGTransform();
newTransform.setMatrix(scalingMatrix);
source.transform.baseVal.initialize(newTransform);
}
function isDescendant(parent, child) {
var node = child.parentNode;
while (node != null) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
}
var destinationElement = document.getElementById("destination");
var inputElement = document.getElementById("input");
while (inputElement.parentNode != null) {
let candidateParent = inputElement.parentNode;
if (isDescendant(candidateParent, destinationElement)) {
break;
}
inputElement = candidateParent;
}
applyTransformations(inputElement, destinationElement);
// Test:
var bboundsTest= document.getElementById("bboundsTest");
const resultBBounds = document.getElementById("input").getBoundingClientRect();
bboundsTest.setAttribute('x', resultBBounds.x);
bboundsTest.setAttribute('y', resultBBounds.y);
bboundsTest.setAttribute('width', resultBBounds.width);
bboundsTest.setAttribute('height', resultBBounds.height);
<svg version="1.2" viewBox="0 0 480 240" width="480" height="240" xmlns="http://www.w3.org/2000/svg">
<g>
<g transform="skewX(10) translate(95,1) rotate(30)">
<g transform="skewX(30) translate(-3,3) rotate(30)">
<g transform="skewX(10) translate(-3,4) rotate(10)">
<rect
id="input"
transform="translate(95,76.5) skewX(25) translate(50,50) scale(1.5) translate(-50,-50) translate(0,0) rotate(45)"
width="30"
height="30"
fill="red"
/>
</g>
</g>
</g>
<rect
id="destination"
x="20"
y="20"
width="100"
height="100"
fill="transparent"
stroke="blue"
/>
<rect
id="bboundsTest"
fill="transparent"
stroke="black"
/>
</g>
</svg>
Note: Both approach will yield different results based on transformations involved on parent elements as second approach doesn't apply all transformations to destination but rather same transformations as parent node of input that is not also parent for destination.
It took me some time to realize an answer, but finally, I got it and it's quite simple!
Get the bounding boxes of both rectangles in the 'screen' coordinates.
For example: getBoundingClientRect.
By comparing the rectangle boxes you can get the desired scaling factors.
While scaling should be done in screen coordinates, we should convert the current element transformation including all the parent transformations to the screen coordinates, transform all those with given scale and convert back to the element coordinates.
Exact line is:
var toScreenMatrix = inputElement.getScreenCTM();
// Scale element by a matrix in screen coordinates and convert it back to the element coordinates:
currentMatrix = currentMatrix.multiply(toScreenMatrix.inverse().multiply(scaleAndTransform).multiply(toScreenMatrix));
This code is generic for all the svg elements, so any shape can be fit into the given rect:
function fitElement(from, to, changePosition) {
var inputElement = document.getElementById(from);
var destinationElement = document.getElementById(to);
// Get center of figure in element coordinates:
var inputScreenBBox = inputElement.getBoundingClientRect();
var destinationScreenBBox = destinationElement.getBoundingClientRect();
var scaleX = destinationScreenBBox.width / inputScreenBBox.width;
var scaleY = destinationScreenBBox.height / inputScreenBBox.height;
var inputCenter = getCenter(inputScreenBBox);
var offsetX = 0;
var offsetY = 0;
if (changePosition) {
var destCenter = getCenter(destinationScreenBBox);
offsetX = destCenter.x - inputCenter.x;
offsetY = destCenter.y - inputCenter.y;
}
// create scale matrix:
var scaleMatrix = getScaleMatrix(scaleX, scaleY, inputElement);
// get element self transformation matrix:
var currentMatrix = getElementMatrix(inputElement);
scaleAndTransform = inputElement.ownerSVGElement.createSVGMatrix()
.translate(offsetX, offsetY)
// Scale in screen coordinates around the element center:
.translate(inputCenter.x, inputCenter.y)
.multiply(scaleMatrix)
.translate(-inputCenter.x, -inputCenter.y)
var toScreenMatrix = inputElement.getScreenCTM();
// Scale element by a matrix in screen coordinates and convert it back to the element coordinates:
currentMatrix = currentMatrix.multiply(toScreenMatrix.inverse().multiply(scaleAndTransform).multiply(toScreenMatrix));
// Apply new created transform back to the element:
var newTransform = inputElement.ownerSVGElement.createSVGTransform();
newTransform.setMatrix(currentMatrix);
inputElement.transform.baseVal.initialize(newTransform);
}
function getElementMatrix(element) {
// Get consolidated element matrix:
var currentMatrix =
(element.transform.baseVal.consolidate() ||
element.ownerSVGElement.createSVGTransform()).matrix;
return currentMatrix;
}
function getScaleMatrix(scaleX, scaleY, el) {
// Return DOM matrix
var svgTransform = el.ownerSVGElement.createSVGTransform();
// Transform type is used because of the bug in chrome applying scale to the DOM matrix:
svgTransform.setScale(scaleX, scaleY);
var scaleMatrix = svgTransform.matrix;
return scaleMatrix
}
function getCenter(rect) {
return new DOMPoint((rect.x + rect.width / 2), (rect.y + rect.height / 2));
}
fitElement('source', 'destination', true);
<svg width="1380" height="1340" xmlns="http://www.w3.org/2000/svg">
<g transform="skewX(10) translate(-3,4) rotate(30)">
<g transform="skewX(30) translate(-3,4) rotate(30)">
<g transform="skewX(10) translate(-3,4) rotate(10)">
<g transform="translate(350,30) skewX(10) rotate(30)">
<rect id="source" transform="scale(2) rotate(30) skewX(10)" x="20" y="50" width="30" height="30"
fill="red" />
</g>
</g>
</g>
</g>
<rect id="destination" x="30" y="30" width="120" height="100" fill="transparent" stroke="blue" />
</svg>
GitHub gist link

How to calculate SVG path current degree

I'm trying to rotate object upon guideline path I created in illustrator.
I did found a way to rotate the object upon the guideline, but It's running on time and not scroll as I wish it to be.
I have this javascript code to determine the path of the object and this animationMotion to rotate the object automatically on time (instead of scroll).
How can I calculate the angle of the object on the path same as animationMotion but base it on scroll instead of time?
Some working codepen without animationMotoion.
function positionTheElement() {
var html = document.documentElement;
var body = document.body;
var scrollPercentage = (html.scrollTop + body.scrollTop - html.clientHeight) / (body.scrollHeight + 600 - html.clientHeight);
var path = document.getElementById("tracker");
var pathLen = path.getTotalLength();
var pt = path.getPointAtLength(scrollPercentage * pathLen );
var element = document.getElementById("wipe");
element.setAttribute("transform", "translate("+ pt.x + "," + pt.y + ")");
};
window.addEventListener("scroll", positionTheElement);
positionTheElement();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<svg>
<g>
<path
id="tracker"
d="M1343.5,32.5
L1341,558C1339.8,583.3 1349.8,600.1 1313,611C1298,619 1247,631 1144,630C1041,629 277,630 277,630C277,630 136,625 136,658C130,687 119,719 126,747C133,775 120,1931 120,1931C120,1931 128,2029.8000000000002 208,2034.4C288,2039 1697.8,2034.4 1697.8,2034.4C1697.8,2034.4 1788,2016 1794,2124C1800,2232 1780,2700 1780,2700C1780,2700 1796.8000000000002,2794 1689.9,2793C1583,2792 938,2787 938,2787L249,2782C249,2782 151.39999999999998,2769.8 154.7,2863.9C158,2958 155,3552 155,3552C155,3552 159,3645.3999999999996 243.5,3632.7C328,3620 1484,3634 1484,3634L1491.8,3999" fill="transparent" stroke-width="0"/>
<!--Wipe-->
<g id="wipe">
<path class="st11" d="M33.3,1c0,0-6.9-14.1-24.7-3.6S-18.5-5.8-23-0.2s-10.3-3.3-10.3-3.3s-3.4,26.2-0.5,24.8
c0.4-0.2,0.6-0.1,0.7,0.3c1.1,2.5-2.4,16.7-2.4,16.7s-3,22.1,0.8,20.7c3.8-1.5-1.4,23.2-1.4,23.2s-7.4,23.6,5.6,2.2
s56.9-26.1,57-15.8s1.1,20.7,3.4-11.3c0.5-6.8,6.3-46.6,0.5-31.9S31.3,4.2,33.3,1z"/>
<line class="st12" x1="-20.3" y1="17.9" x2="-33.3" y2="21.2"/>
<path class="st13" d="M28.1,28.2c0,0-15.7-19.9-23.1-9.8"/>
<path class="st14" d="M26.4,67.4c0,0-0.3-3-9.8-4.2c-9.5-1.2-2.4,1.6-2.4,1.6l13,13.8c0,0-0.3-0.8-0.6-5
C26.5,69.5,26.4,67.4,26.4,67.4L26.4,67.4"/>
<path class="st13" d="M29.1,19l3.5,3.2c-0.7-1.5-3,5.4-4,6.6C27.6,29.9,29.1,19,29.1,19z"/>
<path class="st15" d="M-20.3,17.9c0,0-9.6,12.3-12.7,7.4c0.1-2,0.1-4-0.2-4C-33.5,21.3-20.3,17.9-20.3,17.9z"/>
<path class="st12" d="M-34,58.9c0,0,25.5-19.6,25.8-7.7"/>
<path class="st15" d="M-34.2,58.8l26-7.7C-8.2,51.2-7.1,38.8-34.2,58.8z"/>
</g>
</g>
<!-- IF you run this, the object will auto rotate but on time.
<animateMotion
xlink:href="#wipe"
dur="3s"
begin="0s"
fill="freeze"
repeatCount="indefinite"
rotate="auto"
>
<mpath xlink:href="#tracker" />
</animateMotion>
-->
</svg>
EDIT:
I have tried to add this to get the degrees, the console works but the actual rotate fails to exist.
var firstPoint = path.getPointAtLength(scrollPercentage * pathLen);
var secondPoint = path.getPointAtLength(scrollPercentage * (pathLen + 3));
//Get degree
var deg = Math.atan2(firstPoint.y - secondPoint.y, firstPoint.x - secondPoint.x) * (180 / Math.PI);
console.log(deg);
var element = document.getElementById("wipe");
element.setAttribute("transform", "translate("+ pt.x + "," + pt.y + ") rotate(" + pt.deg + ")");
The degrees works but the transform rotation does not apply.
Error: attribute transform: Expected number, "…7578125)
rotate(undefined)".
You're already calling
var pt = path.getPointAtLength(scrollPercentage * pathLen );
If you call that function again with a small delta in either direction you'll be able to determine the direction of the path. A little trigonometry would then get the rotate you need.

Change SVG fill in a loop

I have simple SVG illustration, is there is any way to change it's color constantly ? like a loop non-stop random color change.
here is my svg
<svg width="533" height="499" viewBox="0 0 533 499" fill="none" xmlns="http://www.w3.org/2000/svg">
This is how I would do it: I'm using colors hsl for the fill and I'm animating the hue of the colors using requestAnimationFrame. I hope it helps.
let p1 = document.querySelectorAll("path")[0];
let p2 = document.querySelectorAll("path")[1]
let h = 0;
function changeColor(){
window.requestAnimationFrame(changeColor);
h+=.5;
h2=210+h;
p1.setAttributeNS(null,"fill", `hsl(${~~h},100%,50%)`);
p2.setAttributeNS(null,"fill", `hsl(${~~h2},100%,50%)`);
}
changeColor()
<svg width="533" height="499" viewBox="0 0 533 499" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M258.089 59.6035C309.803 -3.94652 379.363 78.1818 407.679 127.19C352.338 67.4782 301.718 129.7 287.076 167.787C272.435 205.874 233.694 210.043 205.199 217.679C187.359 222.459 146.446 248.26 128.6 264.085C109.864 289.466 48.3081 292.846 41.8378 268.698C27.0852 213.64 95.5238 148.37 137.644 123.97C163.705 101.458 206.375 123.154 258.089 59.6035Z" fill="blue"/>
<path d="M448.323 394.788C427.389 384.661 420.75 356.279 420.047 343.354C441.009 284.421 527.63 350.762 528.167 368.218C528.703 385.674 474.491 407.447 448.323 394.788Z" fill="red"/>
</svg>
Select the element and recursively call a function that sets the fill attribute of the SVG element you want to recolor with a random hex.
const recolor = element => {
const randomColor = '#'+Math.floor(Math.random()*16777215).toString(16)
circle.setAttribute('fill', randomColor)
setTimeout(() => recolor(element), 600)
}
recolor(document.querySelector('#circle'))
svg circle {
transition: fill .5s linear;
}
<svg height="100" width="100">
<circle id="circle" cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>
fill on <svg> doesnot work. Its for its elements. You can change its background
function random_rgba() {
var o = Math.round, r = Math.random, s = 255;
return 'rgba(' + o(r()*s) + ',' + o(r()*s) + ',' + o(r()*s) + ',' + r().toFixed(1) + ')';
}
function changeColor(){
document.querySelector('svg').style.background = random_rgba();
}
setInterval(changeColor,200);
<svg width="533" height="499" viewBox="0 0 533 499" fill="none" xmlns="http://www.w3.org/2000/svg">

D3 - Drawing a path between DOM elements

I'm creating a parallel coordinates chart. Each circle is a particular brand, and every brand has one circle in each column:
When the user hovers over a circle, I would like to draw a path connecting that circle to the other three circles of the same brand. The issue is that the X position of the circles is random, so I have to draw the line using the circle's modified cx value (and not the data).
Conveniently, I have all four brand circles grouped in their own g elements:
<g class="line-group">
<circle r="5" cx="340.48700997553686" cy="0" data-brand="Brand X"></circle>
<circle r="5" cx="916.9181438059958" cy="59.347826086956466" data-brand="Brand X"></circle>
<circle r="5" cx="1589.2772695723352" cy="229.1306884480747" data-brand="Brand X"></circle>
<circle r="5" cx="2272.275506967826" cy="0" data-brand="Brand X"></circle>
</g>
I can grab the elements, and group the coordinates in a way d3.line() likes, but it makes one line that connects every point.
var line = d3.svg.line()
.interpolate('basis');
var circles = d3.selectAll('.line-group').selectAll('circle'),
circleCoords = [];
circles.forEach( function(d) {
console.log(circles);
for ( i = 0; i < d.length; i++ ) {
var cx = d3.select(d[i]).attr('cx'),
cy = d3.select(d[i]).attr('cy');
circleCoords.push([cx, cy]);
}
});
lineGroup.append('path')
.attr({
'd' : line( circleCoords )
});
How do I structure this so I can grab the cx and cy values of each circle group (the four circles of the same brand inside of g.line-group)?
I probably have to make a custom d attribute, something like this (pseudocode):
path.attr('d', function(d) {
return 'M ' + /* cx of circle 1 */ + ' ' + /* cy of circle 1 */ +
' L ' + /* cx of circle 2 */ + ' ' + /* cy of circle 2 */ +
' L ' + /* cx of circle 3 */ + ' ' + /* cy of circle 3 */ +
' L ' + /* cx of circle 4 */ + ' ' + /* cy of circle 4 */ + ' Z';
})
I believe all the pieces are there, I just can't seem to find a way to put it together correctly. If anyone has any ideas, it would be greatly appreciated!
Edit: Added line definition.
You has the wrong selection (I can't see your line definition, don't forget it):
var svg = d3.selectAll("svg")
var circles = svg.selectAll('.line-group').selectAll("circle"),
// or var circles = svg.selectAll('.line-group > circle'),
circleCoords = [];
circles.forEach( function(d) {
for ( i = 0; i < d.length; i++ ) {
var cx = d3.select(d[i]).attr('cx'),
cy = d3.select(d[i]).attr('cy');
circleCoords.push([cx, cy]);
}
console.log(circleCoords);
});
var line = d3.svg.line()
svg.append('path')
.attr({
'd' : line( circleCoords )
});
Here the working code
Don't forget styles.
You need to identify each '.line-group' or D3 will select all '.line-group' class, may adding id attribute.-
In your case you have multiple "Brands", like so:
<svg>
<g class="line-group">
<circle r="5" cx="10" cy="110" data-brand="Brand-X"></circle>
<circle r="5" cx="30" cy="120" data-brand="Brand-X"></circle>
<circle r="5" cx="150" cy="30" data-brand="Brand-X"></circle>
<circle r="5" cx="290" cy="40" data-brand="Brand-X"></circle>
</g>
<g class="line-group">
<circle r="5" cx="10" cy="10" data-brand="Brand-Y"></circle>
<circle r="5" cx="30" cy="20" data-brand="Brand-Y"></circle>
<circle r="5" cx="150" cy="130" data-brand="Brand-Y"></circle>
<circle r="5" cx="290" cy="140" data-brand="Brand-Y"></circle>
</g>
</svg>
you need to refactory your code:
var svg = d3.selectAll("svg")
var circles = svg.selectAll('.line-group').selectAll("circle"),
circleCoords = [];
var line = d3.svg.line()
// circles.length give you .line-group's count or brand's count:
for (j=0; j<circles.length; j++) {
circles[j].forEach( function(d) { // forEach brand draw a line
var cx = d.getAttribute('cx'),
cy = d.getAttribute('cy');
circleCoords.push([cx, cy]);
})
svg.append('path')
.attr({ 'd' : line( circleCoords ) })
.attr("id","id_"+j);
circleCoords = [];
};
Here's the working code

Categories