Get point's y coordinate on svg path - svg

I guess I need to add some explanation, that I want to ask this question, because too short question doesn't quality standards... funny...
So, here is the question:
How I can get the 'y' coordinate of the point on svg path at a specific 'x' coordinate?

Well this is not straightforward, because a path could have multiple points with the specified x coordinate.
There is no built-in function in the SVG DOM to do this. One solution is to step along the path segments and do the maths yourself.
Alternatively, there is a built in function on SVGPathElement called getPointAtLength(len). You pass in a length along the path and it will return the x,y coords at that point. You could step along the path length and work out where the x coordinate crosses your desired x. You can get the path length from the SVGPathElement.getTotalLength() function. It's a bit of a kludge and you have to be careful you don't miss points where the curve bends near your x. But it should work.
See here for more information on these functions.

I was working on a similar problem and Paul's answer really helped me.
Just to further illustrate #Paul LeBeau's answer, here is a little demo:
let path = document.getElementById("path");
let svg = document.getElementById("svg");
// The first important function getTotalLength
let totalLength = path.getTotalLength();
let intersections = 27;
for(var i = 0; i <= intersections; i ++){
let distance = i * 1/intersections * totalLength;
// The second important function getPointAtLength
let point = path.getPointAtLength(distance);
addCircleToSVG(point.x, point.y);
addTextToSVG(point.x, point.y);
}
function addCircleToSVG(x, y){
let circle = document.createElementNS("http://www.w3.org/2000/svg",'circle');
circle.setAttribute("cx", x);
circle.setAttribute("cy", y);
circle.setAttribute("r", "5");
circle.setAttribute("fill", "#8888ff");
svg.appendChild(circle);
}
function addTextToSVG(x, y){
let text = document.createElementNS("http://www.w3.org/2000/svg",'text');
text.setAttribute("x", x + 10);
text.setAttribute("y", y);
text.setAttribute("fill", "orange");
text.innerHTML = Math.round(y);
svg.appendChild(text);
}
svg{
width:auto;
height: auto;
}
<svg id="svg" viewBox="0 0 1184.25 455.99">
<path id="path" class="st0" d="M0.18,455.53c0,0,73-311,128-311s86,276,122,287s52-22,112-25s114,16,146,18s34,20,64,16s45-144,93-133
s55-21,88-17s58,151,85,149s103-13,128-8s48-21,85-19c37,2,133,43,133,43" fill="#666666"/>
</svg>

If you know all the points of your path, I believe a more performant solution than stepping through the path might be to search the d attribute of your path for the specific x coordinate you are looking for. Then capture the y coordinate using regexp. The regexp could be used like so:
const regex = new RegExp(`${x} ((\d*.\d*))`)
const match = regex.exec(d)

Related

How to know the m or M point of path from all of points in svg?(use raphael.js)

I have an svg picture like this, with M and m in the path. I use raphael.js to calculate. I can get all the points by calling Raphael.getTotalLength(path), but how can I know from which point is the path behind m.
I want to know all the absolute coordinate points of the inner border of the svg, so that I can get a data format similar to the following [[points of the outer border], [points of the inner border]].
This is how I achieved it. I can get all the points, but I can’t distinguish which are the points of the inner frame and which are the points of the outer frame.
import Raphael from 'raphael';
function getPoints(path) {
let points = [];
for (let i = 0; i < Raphael.getTotalLength(path); i += step_point) {
const point = Raphael.getPointAtLength(path, i);
points.push(point);
}
}
This is the svg content:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 120">
<path
d="M72.8525 8.0439c-.405 0-.816.022-1.222.064-4.973.523-8.939 4.112-10.048 8.833-.73-.028-1.453-.043-2.162-.043-5.453 0-10.307.814-14.464 2.423-1.988-3.703-5.849-6.071-10.173-6.071-.973 0-1.949.124-2.899.37-2.994.773-5.508 2.667-7.078 5.331-1.571 2.664-2.01 5.781-1.236 8.775.772 2.986 2.693 5.506 5.301 7.052-1.056 2.419-1.535 4.533-1.814 6.02-.623 3.314-2.519 13.398 5.355 20.728 3.209 2.988 6.672 4.84 10.937 5.8-3.558 4.888-7.226 11.138-8.02 16.945-.349 2.543-.027 4.749.956 6.576l-.149.355c-.034.081-.062.165-.085.25-.315 1.166-.025 2.398.778 3.295.672.754 1.639 1.187 2.649 1.187.044 0 .088-.001.131-.002.27.406.626.758 1.053 1.029.518.33 1.109.519 1.719.55l-1.044 4.167c-.571 2.283.813 4.636 3.086 5.245l10.106 2.708c.372.1.753.15 1.132.15 1.299 0 2.521-.582 3.351-1.595.825-1.008 1.151-2.32.894-3.6-.013-.064-.007-.13.016-.189l1.1-2.829 3.729 6.22c.78 1.3 2.206 2.109 3.723 2.109.759 0 1.509-.202 2.168-.582l9.061-5.232c1.308-.756 2.119-2.108 2.167-3.619.03-.959-.249-1.873-.779-2.627.6-.052 1.175-.255 1.679-.595.42-.283.766-.644 1.024-1.058h.035c1.047 0 2.037-.459 2.713-1.259.778-.92 1.035-2.16.687-3.318-.025-.084-.056-.166-.092-.246l-.158-.35c.933-1.854 1.194-4.068.777-6.6-1.181-7.17-6.763-14.845-10.84-19.646 1.556-.529 3.061-1.122 4.547-1.793 6.708-3.027 9.062-8.913 9.395-11.913.346-3.113-.969-9.08-2.01-12.015-1.056-2.977-3.244-8.332-6.599-12.674 1.647-2.29 2.406-5.105 2.106-7.957-.621-5.911-5.566-10.369-11.503-10.369m0 2c4.84 0 8.997 3.657 9.514 8.578.312 2.97-.769 5.764-2.716 7.735 4.039 4.59 6.48 11.006 7.313 13.355 1.049 2.957 2.192 8.566 1.908 11.126-.285 2.56-2.435 7.696-8.23 10.311-2.229 1.006-4.658 1.897-7.363 2.639.216.171.429.348.617.556 3.231 3.599 10.589 12.513 11.888 20.392.453 2.753-.065 4.727-1.052 6.153l.583 1.294c.149.498.04 1.049-.299 1.451-.296.349-.728.55-1.186.55-.367 0-.722-.13-1.002-.367-.127-.107-.234-.231-.32-.372l-.182-.406c-.053.03-.108.056-.161.085l.17 1.142c.01.521-.245 1.023-.682 1.318-.258.174-.558.266-.867.266-.518 0-.999-.256-1.288-.685-.093-.138-.163-.287-.208-.447l-.078-.525s0 .001-.001.001c-.092.021-.184.022-.277.035-.125.259-.314.488-.566.645-.247.154-.531.235-.82.235-.22 0-.427-.055-.621-.14l1.058 2.404c.18.409.472.758.845 1.006 1.444.961 1.377 3.104-.126 3.973l-9.061 5.23c-.368.213-.77.315-1.168.315-.795 0-1.57-.407-2.008-1.137l-4.403-7.347c-.752-.015-1.524-.056-2.306-.11l-1.698 4.368c-.163.417-.202.87-.114 1.309.3 1.49-.864 2.801-2.284 2.801-.201 0-.407-.026-.614-.082l-10.106-2.708c-1.234-.33-1.974-1.589-1.664-2.827l1.907-7.612c-.062-.027-.127-.044-.185-.077-.256-.151-.451-.374-.584-.631-.092-.01-.185-.009-.278-.027 0 0-.001 0-.001-.001l-.065.532c-.04.159-.105.309-.193.448-.287.45-.777.72-1.312.72-.294 0-.582-.084-.832-.243-.444-.283-.713-.777-.717-1.298l.139-1.147c-.054-.027-.11-.052-.163-.081l-.174.415c-.082.142-.184.268-.307.377-.285.254-.652.395-1.034.395-.441 0-.864-.19-1.158-.519-.35-.392-.474-.939-.339-1.441l.548-1.311c-1.026-1.397-1.598-3.356-1.219-6.121.917-6.699 6.151-14.247 9.637-18.644-4.885-.547-9.142-2.083-13.173-5.836-6.746-6.28-5.521-14.805-4.752-18.894.384-2.041 1.039-4.558 2.526-7.33-2.881-1.035-5.218-3.424-6.041-6.612-1.324-5.122 1.756-10.347 6.877-11.67.802-.207 1.607-.306 2.399-.306 4.097 0 7.844 2.654 9.119 6.698 5.236-2.473 11.057-3.05 15.518-3.05 1.264 0 2.419.047 3.42.109 0 0 .169.006.449.024.281-4.587 3.828-8.437 8.55-8.934.34-.035.678-.053 1.013-.053"
fill="#F00" stroke="#000" />
</svg>
I really look forward to your answers, thank you!
As I mentioned elsewhere. You can split on M. If for some reason this doesn't make sense (as you mentioned multiple 'm's) as you say "behind m", then you need to amend your question to be more precise about where the split would be, if this is part of a more generic issue.
So we can split the string on "m"
var match = new RegExp("(^[^m]*)(.*)", "").exec(path);
And get the last point of the first path part...
var point = Raphael.getPointAtLength(match[1], p.getTotalLength(match[1]));
Then add the final point to the first path...
var p2 = r.path("M" + point.x + "," + point.y + match[2]).attr('stroke','blue')
And I've amended getPoints()...
function getPoints(path) {
let points = [];
let step_point = 10;
for (let i = 0; i < path.getTotalLength(); i += step_point) {
const point = path.getPointAtLength(i);
points.push(point);
}
return points;
}
And get the sets of points...
console.log(getPoints(p1));
console.log(getPoints(p2));
jsfiddle showing different colours for outer/inner and it dumps in the console the two sets of points.

Combining two Matrix Transformations under the same Transformation with SVG

My current task is attempting to combine objects with similar matrices under the same transformation matrix. The two matrices will always have the first 4 digits of it's transform be equal. I am having difficulty calculating the x="???" and y="???" for the second tspan. Any help towards the proper equation would be greatly appreciated.
Input
<svg>
<text transform="matrix(0 1 1 0 100 100)"><tspan x=0 y=0>foo</tspan></text>
<text transform="matrix(0 1 1 0 110 110)"><tspan x=0 y=0>bar</tspan></text>
</svg>
Output
<svg>
<text transform="matrix(0 1 1 0 100 100)">
<tspan x="0" y="0">foo</tspan>
<tspan x="???" y="???">bar</tspan>
</text>
</svg>
EDIT 1
I guess my question is more along the lines of given a point (x,y), how do I apply an existing matrix transformation to that point so that the position will not move, but the element will now be nested inside of another element.
EDIT 2
I have got this code to work for matrices with 0s in the (a,d) or (b,c) positions. Slanted/Skewed matrices I still have not got working. Any thoughts on this?
var aX = floatX[0];
var bX = floatX[1];
var cX = floatX[2];
var dX = floatX[3];
var eX = floatX[4];
var fX = floatX[5];
var aY = floatY[0];
var bY = floatY[1];
var cY = floatY[2];
var dY = floatY[3];
var eY = floatY[4];
var fY = floatY[5];
var xX = (eX * aX) + (fX * bX);
var xY = (eX * cX) + (fX * dX);
var yX = (eY * aY) + (fY * bY);
var yY = (eY * cY) + (fY * dY);
var c1 = cX - aX;
var c2 = dX + bX;
return new float[] { (yX - xX) / (c1 * c2), (yY - xY) / (c1 * c2) };
One thought that may work if my logic isn't flawed, is to find the transform for one element to the other, which can then be used to transform a point of 0,0 (as that's the original x,y) to a new location.
Once we know what the difference in transforms is (assuming that the first 4 figures in the matrix are the same as mentioned in the question, it won't work otherwise), we can figure what the difference in x,y is.
First, there's a bit of code as some browsers have removed this feature..
SVGElement.prototype.getTransformToElement = SVGElement.prototype.getTransformToElement || function(elem) {
return elem.getScreenCTM().inverse().multiply(this.getScreenCTM());
};
This is an svg method that some browsers support, but including as a polyfill in case yours doesn't (like Chrome). It finds the transform from one element to another.
We can then use this, to find the transform from the first to the second text element.
var text1 = document.querySelector('#myText1')
var text2 = document.querySelector('#myText2')
var transform = text2.getTransformToElement( text1 )
Or if you don't want the polyfill, this 'may' work (matrices aren't a strong point of mine!). getCTM() gets the current transformation matrix of an element.
var transform = text1.getCTM().inverse().multiply( text2.getCTM() )
Now we know what the transform between them was. We also know the original x,y was 0,0. So we can create an svg point 0,0 and then transform it with that matrix we've just figured, to find the new x,y.
var pt = document.querySelector('svg').createSVGPoint();
pt.x = 0; pt.y = 0;
var npt = pt.matrixTransform( transform );
Then just a delayed example to show it being moved. Set the tspan with the new x,y we've just figured from the previous transform.
setTimeout( function() {
alert('new x,y is ' + npt.x + ',' + npt.y)
tspan2.setAttribute('x', npt.x);
tspan2.setAttribute('y', npt.y);
},2000);
jsfiddle with polyfill
jsfiddle without polyfill

How to make 161 meter / 528ft circles on with OSMDROID?

I'm using OsmDroid on OpenStreetMaps and can make markers and polylines, but I can't find any examples on how I'd make 161m/528ft circles around a marker.
a) How do I make circles?
b) How do I make them 161m/528ft in size?
Thanks to MKer, I got an idea on how to solve the problem and made this piece of code, which works:
oPolygon = new org.osmdroid.bonuspack.overlays.Polygon(this);
final double radius = 161;
ArrayList<GeoPoint> circlePoints = new ArrayList<GeoPoint>();
for (float f = 0; f < 360; f += 1){
circlePoints.add(new GeoPoint(latitude , longitude ).destinationPoint(radius, f));
}
oPolygon.setPoints(circlePoints);
oMap.getOverlays().add(oPolygon);`
I know this can be optimized. I'm drawing 360 points, no matter what the zoom is!
If you want a "graphical" circle, then you can implement easily your own CircleOverlay, using the DirectedLocationOverlay as a very good starting point.
If you want a "geographical" circle (than will appear more or less as an ellipse), then you can use the OSMBonusPack Polygon, that you will define with this array of GeoPoints:
ArrayList<GeoPoint> circlePoints = new ArrayList<GeoPoint>();
iSteps = (radius * 40000)^2;
fStepSize = M_2_PI/iSteps;
for (double f = 0; f < M_2_PI; f += fStepSize){
circlePoints.add(new GeoPoint(centerLat + radius*sin(f), centerLon + radius*cos(f)));
}
(warning: I translated from a Nominatim piece of code in PHP, without testing)

Get coordinates of svg group on drag with snap.svg

I'm brand new to svg and thought I would try out snap svg. I have a group of circles that I am dragging around, and am looking to get the coordinates of the group. I am using getBBox() to do this, but it isn't working as I would expect. I would expect getBBox() to update its x and y coordinates but it does not seem to do that. It seems simple but I think I am missing something. Here's the code
var lx = 0,
ly = 0,
ox = 0,
oy = 0;
moveFnc = function(dx, dy, x, y) {
var thisBox = this.getBBox();
console.log(thisBox.x, thisBox.y, thisBox);
lx = dx + ox;
ly = dy + oy;
this.transform('t' + lx + ',' + ly);
}
startFnc = function(x, y, e) { }
endFnc = function() {
ox = lx;
oy = ly;
console.log(this.getBBox());
};
var s = Snap("#svg");
var tgroup = s.group();
tgroup.add(s.circle(100, 150, 70), s.circle(200, 150, 70));
tgroup.drag(moveFnc, startFnc, endFnc);
The jsfiddle is at http://jsfiddle.net/STpGe/2/
What am I missing? How would I get the coordinates of the group? Thanks.
As Robert says it won't change. However getBoundingClientRect may help.
this.node.getBoundingClientRect(); //from Raphael
Jsfiddle here showing the difference http://jsfiddle.net/STpGe/3/.
Edit: Actually I'd be tempted to go here first, I found this very useful Get bounding box of element accounting for its transform
Per the SVG specification, getBBox gets the bounding box after transforms have been applied so in the co-ordinate system established by the transform attribute the position is the same.
Imagine like you drew the shape on graph paper setting a transform moves the whole graph paper but when you look at position of the shape on the graph paper it hasn't changed, it's the graph paper that's moved but you're not measuring that.
Try to use the group.matrix object to get x and y coordinate of group object.
moveFnc = function(dx, dy, x, y, event) {
lx = this.matrix.e;
ly = this.matrix.f;
this.transform('translate(' + lx + ',' + ly+')');
}

How to avoid the overlapping of text elements on the TreeMap when child elements are opened in D3.js?

I created a Tree in D3.js based on Mike Bostock's Node-link Tree. The problem I have and that I also see in Mike's Tree is that the text label overlap/underlap the circle nodes when there isn't enough space rather than extend the links to leave some space.
As a new user I'm not allowed to upload images, so here is a link to Mike's Tree where you can see the labels of the preceding nodes overlapping the following nodes.
I tried various things to fix the problem by detecting the pixel length of the text with:
d3.select('.nodeText').node().getComputedTextLength();
However this only works after I rendered the page when I need the length of the longest text item before I render.
Getting the longest text item before I render with:
nodes = tree.nodes(root).reverse();
var longest = nodes.reduce(function (a, b) {
return a.label.length > b.label.length ? a : b;
});
node = vis.selectAll('g.node').data(nodes, function(d, i){
return d.id || (d.id = ++i);
});
nodes.forEach(function(d) {
d.y = (longest.label.length + 200);
});
only returns the string length, while using
d.y = (d.depth * 200);
makes every link a static length and doesn't resize as beautiful when new nodes get opened or closed.
Is there a way to avoid this overlapping? If so, what would be the best way to do this and to keep the dynamic structure of the tree?
There are 3 possible solutions that I can come up with but aren't that straightforward:
Detecting label length and using an ellipsis where it overruns child nodes. (which would make the labels less readable)
scaling the layout dynamically by detecting the label length and telling the links to adjust accordingly. (which would be best but seems really difficult
scale the svg element and use a scroll bar when the labels start to run over. (not sure this is possible as I have been working on the assumption that the SVG needs to have a set height and width).
So the following approach can give different levels of the layout different "heights". You have to take care that with a radial layout you risk not having enough spread for small circles to fan your text without overlaps, but let's ignore that for now.
The key is to realize that the tree layout simply maps things to an arbitrary space of width and height and that the diagonal projection maps width (x) to angle and height (y) to radius. Moreover the radius is a simple function of the depth of the tree.
So here is a way to reassign the depths based on the text lengths:
First of all, I use the following (jQuery) to compute maximum text sizes for:
var computeMaxTextSize = function(data, fontSize, fontName){
var maxH = 0, maxW = 0;
var div = document.createElement('div');
document.body.appendChild(div);
$(div).css({
position: 'absolute',
left: -1000,
top: -1000,
display: 'none',
margin:0,
padding:0
});
$(div).css("font", fontSize + 'px '+fontName);
data.forEach(function(d) {
$(div).html(d);
maxH = Math.max(maxH, $(div).outerHeight());
maxW = Math.max(maxW, $(div).outerWidth());
});
$(div).remove();
return {maxH: maxH, maxW: maxW};
}
Now I will recursively build an array with an array of strings per level:
var allStrings = [[]];
var childStrings = function(level, n) {
var a = allStrings[level];
a.push(n.name);
if(n.children && n.children.length > 0) {
if(!allStrings[level+1]) {
allStrings[level+1] = [];
}
n.children.forEach(function(d) {
childStrings(level + 1, d);
});
}
};
childStrings(0, root);
And then compute the maximum text length per level.
var maxLevelSizes = [];
allStrings.forEach(function(d, i) {
maxLevelSizes.push(computeMaxTextSize(allStrings[i], '10', 'sans-serif'));
});
Then I compute the total text width for all the levels (adding spacing for the little circle icons and some padding to make it look nice). This will be the radius of the final layout. Note that I will use this same padding amount again later on.
var padding = 25; // Width of the blue circle plus some spacing
var totalRadius = d3.sum(maxLevelSizes, function(d) { return d.maxW + padding});
var diameter = totalRadius * 2; // was 960;
var tree = d3.layout.tree()
.size([360, totalRadius])
.separation(function(a, b) { return (a.parent == b.parent ? 1 : 2) / a.depth; });
Now we can call the layout as usual. There is one last piece: to figure out the radius for the different levels we will need a cumulative sum of the radii of the previous levels. Once we have that we simply assign the new radii to the computed nodes.
// Compute cummulative sums - these will be the ring radii
var newDepths = maxLevelSizes.reduce(function(prev, curr, index) {
prev.push(prev[index] + curr.maxW + padding);
return prev;
},[0]);
var nodes = tree.nodes(root);
// Assign new radius based on depth
nodes.forEach(function(d) {
d.y = newDepths[d.depth];
});
Eh voila! This is maybe not the cleanest solution, and perhaps does not address every concern, but it should get you started. Have fun!

Resources