Positioning SVG elements via .getBoundingClientRect() in variable-width div - javascript

I have a bit of an annoying problem.
I'm trying to position a bunch of SVG circle elements according to an existing bunch of SVG text elements that share similar properties.
The circle elements are created in a very separate process than the text elements, so positioning the new elements just using the same transforms etc. as the old one isn't a viable option.
I'm trying to use .getBoundingClientRect() to get the positions since the text elements are transformed into position (so .getBBox() isn't an option) rather than positioned by x and y attributes.
With .getBoundingClientRect(), I can get the correct size/arrangement of the new elements, but since the width of the svg-containing div is variable, there's always a bit of a weird offset that I can't quite account for.
I created a simplified example of my issue here. Resize and refresh the page to see the issue in action.
The code I use to position the circle elements is replicated below.
var circs = theSvg.selectAll("circle")
.data(theCircles)
.enter()
.append("circle")
.attr("r", 15)
.attr("fill", "#f00")
.style("opacity", 0.3)
.attr("transform", function(d){
var sizeDif = 800/(d3.select(".svgTestHolder")[0][0].getBoundingClientRect()["width"]);
var theNum = parseInt(d.split("&")[1]);
var thePosition = theSvg.selectAll("text").filter(function(e){
return e == theNum;})[0];
var theCoords = thePosition[0].getBoundingClientRect();
var leftOffset = d3.select(".svgTestHolder")[0][0].getBoundingClientRect()["left"];
var leftOffset2 = d3.select(".svgTest")[0][0].getBoundingClientRect()["left"];
var bottomOffset = d3.select(".svgTestHolder")[0][0].getBoundingClientRect()["top"];
var bottomOffset2 = d3.select(".svgTest")[0][0].getBoundingClientRect()["top"];
return
"translate(" + ((theCoords["left"] - leftOffset - leftOffset2)
* sizeDif) + "," + ((theCoords["top"] - bottomOffset - bottomOffset2)
* sizeDif) + ")";
})
EDIT:
This is a very delayed update just to note that while I was unable to answer my question as stated, I was able to make a workable solution based on Paul LeBeau's suggestion to extract the transforms from the target element.
In my case, I had to use a series of consecutive transforms rather than a combination of transforming and changing the x/y position (due to certain realities of the project not represented in the linked example). But I'm happy to have found an answer!

Your example works fine for me on Chrome. But really that's only because the SVG is the only thing on the page. If I add some text above the SVG everything goes wrong.
https://jsfiddle.net/rrpfmm6d/1/
Is this the problem you are talking about?
If so, the reason is because you are making the wrong choice in using getBoundingClientRect(). It provides coordinates in screen space. It's origin is the top left of the window (or iframe in the case of jsfiddle).
You should be using getBBox(). The values it returns are in the same coordinate space as the SVG elements. It's origin is (normally) at the top left of the SVG.
In summary, use the coordinates returned by calling getBBox() on your <text> element to calculate the position for your circle. If the circles are inserted into the same SVG as the text, there will be no need to do any adjusting with the div or svg offsets.

Related

SVG: reverse children rotation on parent transform

I'm fiddling around with D3.js in this plunker.
It mostly does what I want, but I noticed a small inconsistency.
The idea is that the 2nd slider rotates the SVG elements in the container. As the elements within are actually text elements, I would like to have them displayed unrotated, and as such, I applied a transform: rotate to them with the symmetric value from the slider.
Although, I noticed that by doing that, the text elements don't rotate around their center, but rather around their top-left corner (I think). This is mostly visible when you observe a point near the edge and see how in transposes the edge on rotation.
I tried already setting both text-anchor and alignment-baseline to middle on these elements, hoping it would offset the text path, but apparently it doesn't change the point around which they pivot when rotated.
Additionally, should I try to set the rotate with pivot point coordinates, it boggles the effect entirely, by applying some translate to the elements, which I can't figure out.
Not sure if getBBox() could help me either in this subject, but I've considered maybe offsetting the points by half their width/height. This seems a bit convoluted though, and I was hoping for an easier/more elegant/cleaner fix.
Any thoughts?
Well, this is awkward. Right after I posted the question, I found an answer in D3.js docs: polygon.centroid().
Basically, I used the return value of this function as the transform: rotate pivot point coordinates and the offset is taken care of. Example (line 99 of the above plunker, rotate() function):
(...)
var textElement = d3.select(this);
return justTranslate+"rotate("+ -value+ textElement.centroid() +")";
(...)
Hope this helps anyone with the same issue.
EDIT: for some reason, Chrome's console says:
Uncaught TypeError: textElement.centroid is not a function
But the behavior is what I was looking for. Have no idea why.
EDIT2: ended up changing the above answer to a getBBox() approach, because the slider movement was bonked because of the previous edit error.
Changed it to this:
text.attr("transform", function(d){
var textElement = d3.select(this);
var current = textElement.attr("transform");
var alreadyRotated = current.indexOf('rotate');
var justTranslate = current.substring(0, alreadyRotated != -1 ? alreadyRotated : current.length);
var bbox = textElement.node().getBBox();
var point = [bbox.x + 0.5*bbox.width, bbox.y + 0.5*bbox.height];
return justTranslate+"rotate("+ -value +" "+ point +")";
});

How to define the node entering position in D3 js force layout

I am trying to implement a radial force layout in D3.js , I saw a similar example but i am stuck on how to initiate the node positions in the layout.
http://bl.ocks.org/vlandham/5087480
Thanks in Advance
Initialising a position is just done by setting the cx and cy positions. The most logical place is where the radius is currently being set i.e.
.attr("r", 10)
.attr("cx", 5) //added
.attr("cy", 5) //added
Of course, you can do something more exotic if you are using the bound data to initialise position.
This will only set the starting point though - the force layout will then take over and position elements. The advantage is that you can potentially reduce some of the initial node movement if you get it right.

Iterating throug SVG elements with D3.js

What I'm trying to do is relatively simple but I'm new to JS and D3.js.
I have created a bunch of rectangles using SVG through D3.js.
I added some code to handle a click event and in there I'd like to iterate through all drawn nodes and do something with them as long as a specific property matches the same property in the one that's been clicked.
Here's the code that draws the rectangles (only one of them here);
d3.select("svg")
.append("rect").attr("x", 50)
.attr("y", 10)
.attr("height", 20)
.attr("width", 200)
.attr("title", "catalog")
.style("fill", "#CB4B19")
.on("click", mouseClick)
And here's how I'm trying to retrieve the "title" property of each rectangle drawn and compare it to the clicked one (and in this case, just log it in the console). I know this is probably basic but I can't figure out what I'm doing wrong here.
function mouseClick(d) {
var t = d3.select(this).attr("title"); //store the "title" property of the clicked rectangle
d3.selectAll("rect").each(function(d, i){ //Select all rectangles drawn
if(d3.select(this).attr("title") == t){ //for each one, if the "title" property = the one initially chosen
console.log(t); //do something here
}
})
}
Your code actually seems to be working correctly. At least for me it did. One thing I will say is that d3 does mimic jQuery syntax in that it lets you select elements with attributes with the d3.select('element[attributeName="?"]') syntax. You can read more about selections here.
So for your example, you could do
var t = d3.select(this).attr("title");
// select all rectangles with the attribute title
d3.selectAll("rect[title='" + t + "']").each(function(d, i){
console.log(t);
});
You no longer need the if statement to check because you are only selecting them. I made a simple jsFiddle to show this. I made 3 different types of rectangles with different title attributes and when you click on them, it only selects rect that have the same title attribute.
http://jsfiddle.net/augburto/znqe8nqr/

Avoid dx/dy attributes in d3 axis labels

I experienced problems with the position of text elements when exporting SVG files and opening it in Corel Draw (some older version). I fixed it by setting every dx/dy attribute to zero and added its value to the corresponding x/y attribute.
I wrote a helper function which is called with .each on every text element I use.
transformDXYtoXY: function(d, i) {
var that = d3.select(this);
var y = that.attr("y") == null ? 0 : parseFloat(that.attr("y"));
var dy = that.attr("dy") == null ? 0 : parseFloat(that.attr("dy"));
that.attr("y", y + dy);
that.attr("dy", 0);
// doing the same with dx/x
...
},
This was working great until I decided to transition axis on input change instead of redraw them:
axis = d3.svg.axis().scale(someScale);
d3.select('.axis')
.transition()
.call(axis)
.selectAll("text")
.each(transformDXYtoXY);
Without the call to transformDXYtoXY() the tick label position is off
The y/dy attributes are not being set, even though when I check for it inside transformDXYtoXY() it seems allright.
Is there a way to tell d3 to avoid using dx/dy? It looks like the problem occurs during transition().
The use of the dx and dy attributes is hardcoded in the source of D3 -- changing it would be a significant effort. However, there's an easy workaround. D3 transitions allow you to set up a listener for the end of the transition. You can leverage this to run your code to fix the attribute values (with minimal changes to your existing code):
d3.select('.axis')
.transition()
.call(axis)
.selectAll("text")
.each("end", transformDXYtoXY);
To clarify, the code that you have at the moment runs the function to fix the attributes immediately after setting up the transition which then runs and overwrites the attribute values. The code above runs the function after the transition is complete, i.e. no further attribute changes will occur.

Reorder elements of SVG ( z-index ) in D3.js

I realise this question has been asked before but I can't get to the bottom of it.
Here is my chart... http://www.gogeye.com/financialnews/piechart/index3.html
All I want to do is have the coin render behind the graph. I know D3 renders in order they are appended.
I have tried to re-append the coin but can't seem to get it working.
I've tried reordering when things are appended in the DOM but keep getting errors probably because variables are getting called before being defined etc.
Can someone give me an example of how to fix this with my code? I don't want you to do the work for me but I've been pulling my hair out for so long, I can't seem to apply other peoples examples to mine.
thanks
I would recommend creating some "layers" using svg g elements which stands for "group".
When you render your chart, you can first define your layers:
var layer1 = svg.append('g');
var layer2 = svg.append('g');
var layer3 = svg.append('g');
// etc... for however many layers you need
Then when you append new elements, you can decide which layer you want them to be on, and it won't matter what order you assign them in, because the group elements have already been added to the DOM, and are ordered. For example:
var layer1 = svg.append('g');
var layer2 = svg.append('g');
var redCircle = layer2.append('circle')
.attr('cx', 50)
.attr('cy', 50)
.attr('r', 16)
.attr('fill', 'red')
var blueSquare = layer1.append('rect')
.attr('x', 25)
.attr('y', 25)
.attr('width', 50)
.attr('height', 50)
.attr('fill', 'blue');
In this case the red circle will be visible above the blue square even though the blue square was created last. This is because the circle and the square are children of different group elements, which are in a pre-defined order.
Here's a FIDDLE of the above example so you can see it in action.
Doing this should take a lot of the guesswork out of when to add certain elements to your chart, and it also helps to organize your elements into a more logical arrangement. Hope that helps, and good luck.
I am using the D3.js, and found that it has a built-in function for changing the z-order of SVG elements programmatically after the original drawing.
RipTutorial: svg--the-drawing-order covers the d3 builtin function
Quotes from this link:
selection.raise(): Re-inserts each selected element, in order, as the last child of its parent. selection.lower(): Re-inserts each selected element, in order, as the first child of its parent.
d3.selectAll("circle").on("mouseenter", function(){
d3.select(this).raise();
});
d3.selectAll("circle").on("mouseleave", function(){
d3.select(this).lower();
});
see live example their jsFiddle

Categories

Resources