d3.js reverse transition does not work - javascript

I am working on horizontal segment bar chart. I want to make it so that the bar chart will animate the colour transition between individual segments depending on the value that is generated randomly every few seconds.
I also have a text box that at the moment says "hello" and it is moving simultaneously with the transition.It works only in one direction from left to right.
I cannot make the colour transition between segments and translating the text box from left to right. From left to right I mean that the number generated last time is greater than the currently generated number. The bar chart should turn off the segments from right to left. But it does it from left to right also the text box is acting weirdly when it comes to reverse translation.
I am also getting this error: g attribute transform: Expected transform function, "null". In my code I want to make a transition on my valueLabel and I think the way I am using is not correct. Despite this error the code gets executed.
My fiddle code is here
Many thanks for suggestions
var configObject = {
svgWidth : 1000,
svgHeight : 1000,
minValue : 1,
maxValue : 100,
midRange : 50,
highRange : 75,
numberOfSegments : 50
};
//define variables
var newValue;
var gaugeValue = configObject.minValue - 1;
var mySegmentMappingScale;
var rectArray=[];
//define svg
var svg = d3.select("body").append("svg")
.attr("width", configObject.svgWidth)
.attr("height", configObject.svgHeight)
.append("g")
.attr("transform", 'translate(' + configObject.svgWidth/2 + ',' + configObject.svgHeight/2 + ')');
//var myG=svg.append('g');
var valueLabel= svg.append("text")
.attr('x',0)
.attr('y', (configObject.svgHeight/13)+15)
.text("hello");
var backgroundRect=svg.append("rect")
.attr("fill", "black")
.attr("x",0)
.attr("y", 0)
.attr("width", (configObject.svgWidth/3))
.attr("height", configObject.svgHeight/13);
for(i = 0; i <= configObject.numberOfSegments; i++){
var myRect=svg.append("rect")
.attr("fill", "#2D2D2D")
.attr("x",i * ((configObject.svgWidth/3)/configObject.numberOfSegments))
.attr("y", 0)
.attr("id","rect"+i)
.attr("width", ((configObject.svgWidth/3)/configObject.numberOfSegments)-3)
.attr("height", configObject.svgHeight/13);
rectArray.push(myRect);
}
//define scale
function setmySegmentMappingScale(){
var domainArray = [];
var x=0;
for(i = configObject.minValue; i <= configObject.maxValue+1; i = i + (configObject.maxValue - configObject.minValue)/configObject.numberOfSegments){
if(Math.floor(i) != domainArray[x-1]){
var temp=Math.floor(i);
domainArray.push(Math.floor(i));
x++;
}
}
var rangeArray = [];
for(i = 0; i <= configObject.numberOfSegments+1; i++){// <=
rangeArray.push(i);
}
mySegmentMappingScale = d3.scale.threshold().domain(domainArray).range(rangeArray);
}
//generate random number
function generate(){
var randomNumber = Math.random() * (configObject.maxValue - configObject.minValue) + configObject.minValue;
newValue = Math.floor(randomNumber);
setmySegmentMappingScale();
animateSVG();
}
function animateSVG(){
var previousSegment = mySegmentMappingScale(gaugeValue) -1;
var newSegment = mySegmentMappingScale(newValue) -1;
if(previousSegment <= -1 && newSegment > -1){
for(i = 0; i <= newSegment; i++){
rectArray[i].transition()
.ease("linear")
.duration(50)
.delay(function(d){return i * 90})
.styleTween("fill", function() { return d3.interpolate( "#2D2D2D","red"); });
valueLabel
.transition().ease("linear")
.duration(50)
.delay(function(d){return i * 90})
.attr("transform","translate(" + (i * ((configObject.svgWidth/3)/configObject.numberOfSegments)+((configObject.svgWidth/3)/configObject.numberOfSegments)) + "," + 0 + ")")
}
}
else if(newSegment > previousSegment){
for(i = previousSegment; i <= newSegment; i++){
rectArray[i].transition()
.ease("linear")
.duration(50)
.delay(function(d){return i * 90})
.styleTween("fill", function() { return d3.interpolate( "#2D2D2D","red"); });
//console.log(temp);
valueLabel
.transition()
.ease("linear")
.duration(50)
.delay(function(d){return i * 90})
.attr("transform","translate(" + (i * ((configObject.svgWidth/3)/configObject.numberOfSegments)+((configObject.svgWidth/3)/configObject.numberOfSegments)) + "," + 0 + ")")
}
}
else if(newSegment < previousSegment){
for(i = previousSegment; i > newSegment; i--){
rectArray[i].transition()
.ease("linear")
.duration(50)
.delay(function(d){return i * 90})
.styleTween("fill", function() { return d3.interpolate( "red","#2D2D2D"); });
valueLabel
.transition()
.ease("linear")
.duration(50)
.delay(function(d){return i * 90})
.attr("transform","translate(" + (i * ((configObject.svgWidth/3)/configObject.numberOfSegments)-((configObject.svgWidth/3)/configObject.numberOfSegments)) + "," + 0 + ")")
}
}
gaugeValue = newValue;
}
setInterval(function() {
generate()
}, 8000);

The problem is just the delay.
When newSegment > previousSegment, you set the delay like this:
.delay(function(d){return i * 90})
Which makes sense, because i is an increasing variable. But, when newSegment < previousSegment the same math doesn't work anymore: i is a decreasing variable, and the delay has to increase as i decreases, not the other way around.
This is what you need:
.delay(function(d){return Math.abs(i -previousSegment)*90})
Here is your updated fiddle: https://jsfiddle.net/b7usw2nr/

Related

Drag a Line with d3.drag-event, on a raster

since two days, I'm trying to move a line in simple 10x10 Raster, using the mouse.
I solved this without any issues, with complex svg-"Symbols" but the simplest Elements bring me to my borders…
Ok, simple line with a g-tag:
var svg = d3.select("#drawing");
const graph = svg.append("g")
.attr("id","1")
.attr("ponter-events","fill")
.call(d3.drag()
.on("start", dragGraphicStart)
.on("drag", dragGraphic)
.on("end", dragGraphicStop));
graph.html("<line class='coldbrinewater graphic' x1='10' y1='10' x2='50' y2='50' />");
Now of Course, before the first drag, this line doesn't have a Transformation, so I check this before reading a Position:
var xPos, yPos;
function dragGraphicStart() {
var trans = d3.select(this).attr("transform"); //Prüfen ob bereits ein Transform existiert
if (trans == null || trans == "" || trans == "translate(0)") { //kein Transform vorhanden
xPos = 0;
yPos = 0;
}
else { //Transform gefunden, startwerte ermitteln
trans = trans.replace(",", " "); //I don't know why, sometimes I got a comma between x and y-value
trans = trans.substring(trans.indexOf("(") + 1, trans.indexOf(")")).split(" ");
xPos = parseInt( trans[0]);
yPos = parseInt( trans[1] );
}
}
And then I try to move the line:
function dragGraphic(d, i) {
xPos += Math.round(d3.event.dx / raster) * raster;
//xPos += d3.event.dx;
yPos += Math.round(d3.event.dy / raster) * raster;
//yPos += d3.event.dy;
d3.select(this).attr("transform", "translate(" + xPos + " " + yPos + ")");
}
with the commented lines xPos += d3.event.dx (and y) it works fine but not if I like to calculate the raster before.
I have no idea why, but then I can see in the console, that translate-attribute often only has one Parameter or is empty. like this:
transform"translate(30)" or transform=""
I built a (non) working example here:
https://jsfiddle.net/Telefisch/3oecj6wd/
Thank you

How to show full text when zoom in & truncate it when zoom out

I am creating a tree chart with d3.js, it works fine... but I want text to react to zooming, Here is the JSFiddle.
Please look at first node... it has lots of characters (in my case max will be 255)
When zoomed in or out, my text remains same, but I want to see all on zoom in.
var json = {
"name": "Maude Charlotte Licia Fernandez Maude Charlotte Licia Fernandez Maude Charlotte Licia Fernandez Maude Charlotte Licia FernandezMaude Charlotte Licia Fernandez Maude Charlotte Licia Fernandez Maude Charlotte Licia Fernandez Maude asdlkhkjh asd asdsd",
"id": "06ada7cd-3078-54bc-bb87-72e9d6f38abf",
"_parents": [{
"name": "Janie Clayton Norton",
"id": "a39bfa73-6617-5e8e-9470-d26b68787e52",
"_parents": [{
"name": "Pearl Cannon",
"id": "fc956046-a5c3-502f-b853-d669804d428f",
"_parents": [{
"name": "Augusta Miller",
"id": "fa5b0c07-9000-5475-a90e-b76af7693a57"
}, {
"name": "Clayton Welch",
"id": "3194517d-1151-502e-a3b6-d1ae8234c647"
}]
}, {
"name": "Nell Morton",
"id": "06c7b0cb-cd21-53be-81bd-9b088af96904",
"_parents": [{
"name": "Lelia Alexa Hernandez",
"id": "667d2bb6-c26e-5881-9bdc-7ac9805f96c2"
}, {
"name": "Randy Welch",
"id": "104039bb-d353-54a9-a4f2-09fda08b58bb"
}]
}]
}, {
"name": "Helen Donald Alvarado",
"id": "522266d2-f01a-5ec0-9977-622e4cb054c0",
"_parents": [{
"name": "Gussie Glover",
"id": "da430aa2-f438-51ed-ae47-2d9f76f8d831",
"_parents": [{
"name": "Mina Freeman",
"id": "d384197e-2e1e-5fb2-987b-d90a5cdc3c15"
}, {
"name": "Charlotte Ahelandro Martin",
"id": "ea01728f-e542-53a6-acd0-6f43805c31a3"
}]
}, {
"name": "Jesus Christ Pierce",
"id": "bfd1612c-b90d-5975-824c-49ecf62b3d5f",
"_parents": [{
"name": "Donald Freeman Cox",
"id": "4f910be4-b827-50be-b783-6ba3249f6ebc"
}, {
"name": "Alex Fernandez Gonzales",
"id": "efb2396d-478a-5cbc-b168-52e028452f3b"
}]
}]
}]
};
var boxWidth = 250,
boxHeight = 100;
// Setup zoom and pan
var zoom = d3.behavior.zoom()
.scaleExtent([.1, 1])
.on('zoom', function() {
svg.attr("transform", "translate(" + d3.event.translate + ") scale(" + d3.event.scale + ")");
})
// Offset so that first pan and zoom does not jump back to the origin
.translate([600, 600]);
var svg = d3.select("body").append("svg")
.attr('width', 1000)
.attr('height', 500)
.call(zoom)
.append('g')
// Left padding of tree so that the whole root node is on the screen.
// TODO: find a better way
.attr("transform", "translate(150,200)");
var tree = d3.layout.tree()
// Using nodeSize we are able to control
// the separation between nodes. If we used
// the size parameter instead then d3 would
// calculate the separation dynamically to fill
// the available space.
.nodeSize([100, 200])
// By default, cousins are drawn further apart than siblings.
// By returning the same value in all cases, we draw cousins
// the same distance apart as siblings.
.separation(function() {
return .9;
})
// Tell d3 what the child nodes are. Remember, we're drawing
// a tree so the ancestors are child nodes.
.children(function(person) {
return person._parents;
});
var nodes = tree.nodes(json),
links = tree.links(nodes);
// Style links (edges)
svg.selectAll("path.link")
.data(links)
.enter().append("path")
.attr("class", "link")
.attr("d", elbow);
// Style nodes
var node = svg.selectAll("g.person")
.data(nodes)
.enter().append("g")
.attr("class", "person")
.attr("transform", function(d) {
return "translate(" + d.y + "," + d.x + ")";
});
// Draw the rectangle person boxes
node.append("rect")
.attr({
x: -(boxWidth / 2),
y: -(boxHeight / 2),
width: boxWidth,
height: boxHeight
});
// Draw the person's name and position it inside the box
node.append("text")
.attr("text-anchor", "start")
.attr('class', 'name')
.text(function(d) {
return d.name;
});
// Text wrap on all nodes using d3plus. By default there is not any left or
// right padding. To add padding we would need to draw another rectangle,
// inside of the rectangle with the border, that represents the area we would
// like the text to be contained in.
d3.selectAll("text").each(function(d, i) {
d3plus.textwrap()
.container(d3.select(this))
.valign("middle")
.draw();
});
/**
* Custom path function that creates straight connecting lines.
*/
function elbow(d) {
return "M" + d.source.y + "," + d.source.x + "H" + (d.source.y + (d.target.y - d.source.y) / 2) + "V" + d.target.x + "H" + d.target.y;
}
body {
text-align: center;
}
svg {
margin-top: 32px;
border: 1px solid #aaa;
}
.person rect {
fill: #fff;
stroke: steelblue;
stroke-width: 1px;
}
.person {
font: 14px sans-serif;
}
.link {
fill: none;
stroke: #ccc;
stroke-width: 1.5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3plus/1.8.0/d3plus.min.js"></script>
I made a sample of your requirement in this fiddle
It may need some more tweaking to position the text vertical middle; but this can be the base for you to work on. Calculations are done in the function wrap() and call on page load and zooming.
function wrap() {
var texts = d3.selectAll("text"),
lineHeight = 1.1, // ems
padding = 2, // px
fSize = scale > 1 ? fontSize / scale : fontSize,
// find how many lines can be included
lines = Math.floor((boxHeight - (2 * padding)) / (lineHeight * fSize)) || 1;
texts.each(function(d, i) {
var text = d3.select(this),
words = d.name.split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
tspan = text.text(null).append("tspan").attr("dy", "-0.5em").style("font-size", fSize + "px");
while ((word = words.pop())) {
line.push(word);
tspan.text(line.join(" "));
// check if the added word can fit in the box
if ((tspan.node().getComputedTextLength() + (2 * padding)) > boxWidth) {
// remove current word from line
line.pop();
tspan.text(line.join(" "));
lineNumber++;
// check if a new line can be placed
if (lineNumber > lines) {
// left align text of last line
tspan.attr("x", (tspan.node().getComputedTextLength() - boxWidth) / 2 + padding);
--lineNumber;
break;
}
// create new line
tspan.text(line.join(" "));
line = [word]; // place the current word in new line
tspan = text.append("tspan")
.style("font-size", fSize + "px")
.attr("dy", "1em")
.text(word);
}
// left align text
tspan.attr("x", (tspan.node().getComputedTextLength() - boxWidth) / 2 + padding);
}
// align vertically inside the box
text.attr("text-anchor", "middle").attr("y", padding - (lineHeight * fSize * lineNumber) / 2);
});
}
Also note that I've added the style dominant-baseline: hanging; to .person class
The code in this jsfiddle is an attempt to address the performance issues that you have with very large tree charts. A delay is set with setTimeout in the zoom event handler to allow zooming at "full speed", without text resizing. Once the zooming stops for a short time, the text is rearranged according to the new scaling:
var scaleValue = 1;
var refreshTimeout;
var refreshDelay = 0;
var zoom = d3.behavior.zoom()
.scaleExtent([.1, 1.5])
.on('zoom', function () {
svg.attr("transform", "translate(" + d3.event.translate + ") scale(" + d3.event.scale + ")");
scaleValue = d3.event.scale;
if (refreshTimeout) {
clearTimeout(refreshTimeout);
}
refreshTimeout = setTimeout(function () {
wrapText();
}, refreshDelay);
})
The delay (in milliseconds) depends on the number of nodes in the tree. You can experiment with the mathematical expression to find the best parameters for the wide range of node counts that you expect in your tree.
// Calculate the refresh delay
refreshDelay = Math.pow(node.size(), 0.5) * 2.0;
You can also set the parameters in calcFontSize to fit your needs:
// Calculate the font size for the current scaling
var calcFontSize = function () {
return Math.min(24, 10 * Math.pow(scaleValue, -0.25))
}
The initialization of the nodes has been slightly modified:
node.append("rect")
.attr({
x: 0,
y: -(boxHeight / 2),
width: boxWidth,
height: boxHeight
});
node.append("text")
.attr("text-anchor", "start")
.attr("dominant-baseline", "middle")
.attr('class', 'name')
.text(function (d) {
return d.name;
});
And the text is processed in wrapText:
// Adjust the font size to the zoom level and wrap the text in the container
var wrapText = function () {
d3.selectAll("text").each(function (d, i) {
var $text = d3.select(this);
if (!$text.attr("data-original-text")) {
// Save original text in custom attribute
$text.attr("data-original-text", $text.text());
}
var content = $text.attr("data-original-text");
var tokens = content.split(/(\s)/g);
var strCurrent = "";
var strToken = "";
var box;
var lineHeight;
var padding = 4;
$text.text("").attr("font-size", calcFontSize());
var $tspan = $text.append("tspan").attr("x", padding).attr("dy", 0);
while (tokens.length > 0) {
strToken = tokens.shift();
$tspan.text((strCurrent + strToken).trim());
box = $text.node().getBBox();
if (!lineHeight) {
lineHeight = box.height;
}
if (box.width > boxWidth - 2 * padding) {
$tspan.text(strCurrent.trim());
if (box.height + lineHeight < boxHeight) {
strCurrent = strToken;
$tspan = $text.append("tspan").attr("x", padding).attr("dy", lineHeight).text(strCurrent.trim());
} else {
break;
}
}
else {
strCurrent += strToken;
}
}
$text.attr("y", -(box.height - lineHeight) / 2);
});
}
Text wrapping can be process intensive if we have a lot of text. To address those issues, present in my first answer, this new version has improved performance, thanks to pre-rendering.
This script creates an element outside of the DOM, and stores all nodes and edges into it. Then it checks which elements would be visible, removing them from the DOM, and adding them back when appropriate.
I'm making use of jQuery for data(), and for selecting elements. In my example on the fiddle, there are 120 nodes. But it should work similarly for much more, as the only nodes rendered are the ones on screen.
I changed the zoom behaviour, so that the zoom is centered on the mouse cursor, and was surprised to see that the pan / zoom works on iOS as well.
See it in action.
UPDATE
I applied the timeout (ConnorsFan's solution), as it makes a big difference. In addition, I added a minimum scale for which text should be re-wrapped.
$(function() {
var viewport_width = $(window).width(),
viewport_height = $(window).height(),
node_width = 120,
node_height = 60,
separation_width = 100,
separation_height = 55,
node_separation = 0.78,
font_size = 20,
refresh_delay = 200,
refresh_timeout,
zoom_extent = [0.5, 1.15],
// Element outside DOM, to calculate pre-render
buffer = $("<div>");
// Parse "transform" attribute
function parse_transform(input_string) {
var transformations = {},
matches, seek;
for (matches in input_string = input_string.match(/(\w+)\(([^,)]+),?([^)]+)?\)/gi)) {
seek = input_string[matches].match(/[\w.\-]+/g), transformations[seek.shift()] = seek;
}
return transformations;
}
// Adapted from ConnorsFan's answer
function get_font_size(scale) {
fs = ~~Math.min(font_size, 15 * Math.pow(scale, -0.25));
fs = ~~(((font_size / scale) + fs) / 2)
return [fs, fs]
}
// Use d3plus to wrap the text
function wrap_text(scale) {
if (scale > 0.75) {
$("svg > g > g").each(function(a, b) {
f = $(b);
$("text", f)
.text(f.data("text"));
});
d3.selectAll("text").each(function(a, b) {
d3_el = d3.select(this);
d3plus.textwrap()
.container(d3_el)
.align("center")
.valign("middle")
.width(node_width)
.height(node_height)
.valign("middle")
.resize(!0)
.size(get_font_size(scale))
.draw();
});
}
}
// Handle pre-render (remove elements that leave viewport, add them back when appropriate)
function pre_render() {
buffer.children("*")
.each(function(i, el) {
d3.transform(d3.select(el).attr("transform"));
var el_path = $(el)[0],
svg_wrapper = $("svg"),
t = parse_transform($("svg > g")[0].getAttribute("transform")),
element_data = $(el_path).data("coords"),
element_min_x = ~~element_data.min_x,
element_max_x = ~~element_data.max_x,
element_min_y = ~~element_data.min_y,
element_max_y = ~~element_data.max_y,
svg_wrapper_width = svg_wrapper.width(),
svg_wrapper_height = svg_wrapper.height(),
s = parseFloat(t.scale),
x = ~~t.translate[0],
y = ~~t.translate[1];
if (element_min_x * s + x <= svg_wrapper_width &&
element_min_y * s + y <= svg_wrapper_height &&
0 <= element_max_x * s + x &&
0 <= element_max_y * s + y) {
if (0 == $("#" + $(el).prop("id")).length) {
if (("n" == $(el).prop("id").charAt(0))) {
// insert nodes above edges
$(el).clone(1).appendTo($("svg > g"));
wrap_text(scale = t.scale);
} else {
// insert edges
$(el).clone(1).prependTo($("svg > g"));
}
}
} else {
id = $(el).prop("id");
$("#" + id).remove();
}
});
}
d3.scale.category20();
var link = d3.select("body")
.append("svg")
.attr("width", viewport_width)
.attr("height", viewport_height)
.attr("pointer-events", "all")
.append("svg:g")
.call(d3.behavior.zoom().scaleExtent(zoom_extent)),
layout_tree = d3.layout.tree()
.nodeSize([separation_height * 2, separation_width * 2])
.separation(function() {
return node_separation;
})
.children(function(a) {
return a._parents;
}),
nodes = layout_tree.nodes(json),
edges = layout_tree.links(nodes);
// Style links (edges)
link.selectAll("path.link")
.data(edges)
.enter()
.append("path")
.attr("class", "link")
.attr("d", function(a) {
return "M" + a.source.y + "," + a.source.x + "H" + ~~(a.source.y + (a.target.y - a.source.y) / 2) + "V" + a.target.x + "H" + a.target.y;
});
// Style nodes
var node = link.selectAll("g.person")
.data(nodes)
.enter()
.append("g")
.attr("transform", function(a) {
return "translate(" + a.y + "," + a.x + ")";
})
.attr("class", "person");
// Draw the rectangle person boxes
node.append("rect")
.attr({
x: -(node_width / 2),
y: -(node_height / 2),
width: node_width,
height: node_height
});
// Draw the person's name and position it inside the box
node_text = node.append("text")
.attr("text-anchor", "start")
.text(function(a) {
return a.name;
});
// Text wrap on all nodes using d3plus. By default there is not any left or
// right padding. To add padding we would need to draw another rectangle,
// inside of the rectangle with the border, that represents the area we would
// like the text to be contained in.
d3.selectAll("text")
.each(function(a, b) {
d3plus.textwrap()
.container(d3.select(this))
.valign("middle")
.resize(!0)
.size(get_font_size(1))
.draw();
});
// START Create off-screen render
// Append node edges to memory, to allow pre-rendering
$("svg > g > path")
.each(function(a, b) {
el = $(b)[0];
if (d = $(el)
.attr("d")) {
// Parse d parameter from rect, in the format found in the d3 tree dom: M0,0H0V0V0
for (var g = d.match(/([MLQTCSAZVH])([^MLQTCSAZVH]*)/gi), c = g.length, h, k, f, l, m = [], e = [], n = 0; n < c; n++) {
command = g[n], void 0 !== command && ("M" == command.charAt(0) ? (coords = command.substring(1, command.length), m.push(~~coords.split(",")[0]), e.push(~~coords.split(",")[1])) : "V" == command.charAt(0) ? e.push(~~command.substring(1, command.length)) : "H" == command.charAt(0) && m.push(~~command.substring(1, command.length)));
}
0 < m.length && (h = Math.min.apply(this, m), f = Math.max.apply(this, m));
0 < e.length && (k = Math.min.apply(this, e), l = Math.max.apply(this, e));
$(el).data("position", a);
$(el).prop("id", "e" + a);
$(el).data("coords", {
min_x: h,
min_y: k,
max_x: f,
max_y: l
});
// Store element coords in memory
hidden_element = $(el).clone(1);
buffer.append(hidden_element);
}
});
// Append node elements to memory
$("svg > g > g").each(function(a, b) {
el = $("rect", b);
transform = b.getAttribute("transform");
null !== transform && void 0 !== transform ? (t = parse_transform(transform), tx = ~~t.translate[0], ty = ~~t.translate[1]) : ty = tx = 0;
// Calculate element area
el_min_x = ~~el.attr("x");
el_min_y = ~~el.attr("y");
el_max_x = ~~el.attr("x") + ~~el.attr("width");
el_max_y = ~~el.attr("y") + ~~el.attr("height");
$(b).data("position", a);
$(b).prop("id", "n" + a);
$(b).data("coords", {
min_x: el_min_x + tx,
min_y: el_min_y + ty,
max_x: el_max_x + tx,
max_y: el_max_y + ty
});
text_el = $("text", $(b));
0 < text_el.length && $(b).data("text", d3.select(text_el[0])[0][0].__data__.name);
// Store element coords in memory
hidden_element = $(b).clone(1);
// store node in memory
buffer.append(hidden_element);
});
// END Create off-screen render
d3_svg = d3.select("svg");
svg_group = d3.select("svg > g");
// Setup zoom and pan
zoom = d3.behavior.zoom()
.on("zoom", function() {
previous_transform = $("svg > g")[0].getAttribute("transform");
svg_group.style("stroke-width", 1.5 / d3.event.scale + "px");
svg_group.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
pre_render();
if (previous_transform !== null) {
previous_transform = parse_transform(previous_transform);
if (previous_transform.scale != d3.event.scale) {
// ConnorsFan's solution
if (refresh_timeout) {
clearTimeout(refresh_timeout);
}
scale = d3.event.scale;
refresh_timeout = setTimeout(function() {
wrap_text(scale = scale);
}, refresh_delay, scale);
}
}
});
// Apply initial zoom / pan
d3_svg.call(zoom);
});

How to remove data cleanly before updating d3.js chart?

I'm quite new to D3 and been working through trying to figure everything out. I'm trying to configure this example here to update with new data and transition appropriately.
Here is the code pen I have configured (click the submit to update)
http://codepen.io/anon/pen/pbjLRW?editors=1010
From what I can gather, using some variation of .exit() is required for a clean data transition, but after reading some tutorials I'm still finding it difficult to know how it works. I have seen examples where simply removing the containers before calling the draw function works, but in my limited experience it can cause a flicker when changing data so I'm not sure if it's best practice?
Now, I'm not sure why the data is not updating correctly in my codepen, but my main concern is trying to get the transition right. Ideally I would like to know how I could just move the needle when changing data, so It would go from 90 > 40 for example, instead of 90 > 0 > 40.
However, I will definitely settle for figuring out why it doesn't redraw itself in the same location once clicking submit in the linked codepen.
Here is my update function;
function updateGuage() {
d3.selectAll("text").remove()
d3.selectAll('.needle').remove()
chart.remove()
name = "qwerty";
value = "25";
drawGuage();
}
initial draw;
function drawGuage() {
percToDeg = function(perc) {
return perc * 360;
};
percToRad = function(perc) {
return degToRad(percToDeg(perc));
};
degToRad = function(deg) {
return deg * Math.PI / 180;
};
// Create SVG element
svg = el.append('svg').attr('width', width + margin.left + margin.right).attr('height', height + margin.top + margin.bottom);
// Add layer for the panel
chart = svg.append('g').attr('transform', "translate(" + ((width + margin.left) / 2) + ", " + ((height + margin.top) / 2) + ")");
chart.append('path').attr('class', "arc chart-first");
chart.append('path').attr('class', "arc chart-second");
chart.append('path').attr('class', "arc chart-third");
arc3 = d3.svg.arc().outerRadius(radius - chartInset).innerRadius(radius - chartInset - barWidth)
arc2 = d3.svg.arc().outerRadius(radius - chartInset).innerRadius(radius - chartInset - barWidth)
arc1 = d3.svg.arc().outerRadius(radius - chartInset).innerRadius(radius - chartInset - barWidth)
repaintGauge = function() {
perc = 0.5;
var next_start = totalPercent;
arcStartRad = percToRad(next_start);
arcEndRad = arcStartRad + percToRad(perc / 3);
next_start += perc / 3;
arc1.startAngle(arcStartRad).endAngle(arcEndRad);
arcStartRad = percToRad(next_start);
arcEndRad = arcStartRad + percToRad(perc / 3);
next_start += perc / 3;
arc2.startAngle(arcStartRad + padRad).endAngle(arcEndRad);
arcStartRad = percToRad(next_start);
arcEndRad = arcStartRad + percToRad(perc / 3);
arc3.startAngle(arcStartRad + padRad).endAngle(arcEndRad);
chart.select(".chart-first").attr('d', arc1);
chart.select(".chart-second").attr('d', arc2);
chart.select(".chart-third").attr('d', arc3);
}
/////////
var texts = svg.selectAll("text")
.data(dataset)
.enter();
texts.append("text")
.text(function() {
return dataset[0].metric;
})
.attr('id', "Name")
.attr('transform', "translate(" + ((width + margin.left) / 6) + ", " + ((height + margin.top) / 1.5) + ")")
.attr("font-size", 25)
.style("fill", "#000000");
var trX = 180 - 210 * Math.cos(percToRad(percent / 2));
var trY = 195 - 210 * Math.sin(percToRad(percent / 2));
// (180, 195) are the coordinates of the center of the gauge.
displayValue = function() {
texts.append("text")
.text(function() {
return dataset[0].value;
})
.attr('id', "Value")
.attr('transform', "translate(" + trX + ", " + trY + ")")
.attr("font-size", 18)
.style("fill", '#000000');
}
texts.append("text")
.text(function() {
return 0;
})
.attr('id', 'scale0')
.attr('transform', "translate(" + ((width + margin.left) / 100) + ", " + ((height + margin.top) / 2) + ")")
.attr("font-size", 15)
.style("fill", "#000000");
texts.append("text")
.text(function() {
return gaugeMaxValue / 2;
})
.attr('id', 'scale10')
.attr('transform', "translate(" + ((width + margin.left) / 2.15) + ", " + ((height + margin.top) / 30) + ")")
.attr("font-size", 15)
.style("fill", "#000000");
texts.append("text")
.text(function() {
return gaugeMaxValue;
})
.attr('id', 'scale20')
.attr('transform', "translate(" + ((width + margin.left) / 1.03) + ", " + ((height + margin.top) / 2) + ")")
.attr("font-size", 15)
.style("fill", "#000000");
var Needle = (function() {
//Helper function that returns the `d` value for moving the needle
var recalcPointerPos = function(perc) {
var centerX, centerY, leftX, leftY, rightX, rightY, thetaRad, topX, topY;
thetaRad = percToRad(perc / 2);
centerX = 0;
centerY = 0;
topX = centerX - this.len * Math.cos(thetaRad);
topY = centerY - this.len * Math.sin(thetaRad);
leftX = centerX - this.radius * Math.cos(thetaRad - Math.PI / 2);
leftY = centerY - this.radius * Math.sin(thetaRad - Math.PI / 2);
rightX = centerX - this.radius * Math.cos(thetaRad + Math.PI / 2);
rightY = centerY - this.radius * Math.sin(thetaRad + Math.PI / 2);
return "M " + leftX + " " + leftY + " L " + topX + " " + topY + " L " + rightX + " " + rightY;
};
function Needle(el) {
this.el = el;
this.len = width / 2.5;
this.radius = this.len / 8;
}
Needle.prototype.render = function() {
this.el.append('circle').attr('class', 'needle-center').attr('cx', 0).attr('cy', 0).attr('r', this.radius);
return this.el.append('path').attr('class', 'needle').attr('id', 'client-needle').attr('d', recalcPointerPos.call(this, 0));
};
Needle.prototype.moveTo = function(perc) {
var self,
oldValue = this.perc || 0;
this.perc = perc;
self = this;
// Reset pointer position
this.el.transition().delay(100).ease('quad').duration(200).select('.needle').tween('reset-progress', function() {
return function(percentOfPercent) {
var progress = (1 - percentOfPercent) * oldValue;
repaintGauge(progress);
return d3.select(this).attr('d', recalcPointerPos.call(self, progress));
};
});
this.el.transition().delay(300).ease('bounce').duration(1500).select('.needle').tween('progress', function() {
return function(percentOfPercent) {
var progress = percentOfPercent * perc;
repaintGauge(progress);
return d3.select(this).attr('d', recalcPointerPos.call(self, progress));
};
});
};
return Needle;
})();
needle = new Needle(chart);
needle.render();
needle.moveTo(percent);
setTimeout(displayValue, 1350);
}
Any help/advice is much appreciated,
Thanks
What you wanna check out is How selections work written by Mike Bostock. After reading this article, everything around enter, update and exit selections will become clearer.
In a nutshell:
You create a selection of elements with selectAll('li')
You join the selection with a data array through calling data([...])
Now D3 compares what's already in the DOM with the joined data. Each DOM element processed this way has a __data__ property that allows D3 to bind a data item to an element.
After you've joined data, you receive the enter selection by calling enter(). This is every data element that has not yet been bound to the selected DOM elements. Typically you use the enter selection to create new elements, e.g. through append()
By calling exit() you receive the exit selection. These are all already existing DOM elements which no longer have an associated data item after the join. Typically you use the exit selection to remove DOM elements with remove()
The so called update selection is the one thing that's been returned after joining the selection with data(). You will want to store the update selection in a variable, so you have access to it even after calling enter() or exit().
Note the difference between d3v3 and d3v4:
In d3v3, when you've already added elements via the enter selection, the update selection includes those newly created DOM elements as well. It's crucial to know that the update selection changes after you've created new elements.
However, this is no longer true when using d3v4. The change log says
"In addition, selection.append no longer merges entering nodes into the update selection; use selection.merge to combine enter and update after a data join."
It is important to know that there are three different operations you can perform after binding data. Handle additions, deletions and modify things that did not change (or have been added just before).
Here is an example creating and manipulating a simple list: http://jsbin.com/sekuhamico/edit?html,css,js,output
var update = () => {
// bind data to list elements
// think of listWithData as a virtual representation of
// the array of list items you will later see in the
// DOM. d3.js does not handle the mapping from this
// virtual structure to the DOM for you. It is your task
// to define what is to happen with elements that are
// added, removed or updated.
var listWithData = ul.selectAll('li').data(listItems);
// handle additions
// by calling enter() on our virtual list, you get the
// subset of entries which need to be added to the DOM
// as their are not yet present there.
listWithData.enter().append('li').text(i => i.text).on('click', i => toggle(i));
// handle removal
// by calling exit() on our virtual list, you get the
// subset of entries which need to be removed from the
// DOM as they are not longer present in the virtual list.
listWithData.exit().remove();
// update existing
// acting directly on the virtual list will update any
// elements currently present in the DOM. If you would
// execute this line before calling exit(), you would
// also manipulate those items to be removed. If you
// would even call it before calling enter() you would
// miss on updating the newly added element.
listWithData.attr('class', i => i.active ? 'active' : '');
};
Be aware that in reality you probably need to add some sort of id to your items. To ensure the right items are removed and you do not get ordering issues.
Explanation
The update function knows nothing about what, or even if anything has changed. It does not know, nor care, if there are new data elements or if old ones have been removed. But both things could happen. Therefore we handle both cases by calling enter() and exit() respectively. The d3 functions enter() and exit() provides us with the subsets of list elements that should be added or removed. Finally we need to take care of changes in the existing data.
var listItems = [{ text: 1, active: false}, { text: 2, active: true}];
var ul = d3.select('#id').append('ul');
var update = () => {
var listWithData = ul.selectAll('li').data(listItems);
// add new
listWithData.enter().append('li').text(i => i.text).on('click', i => toggle(i));
// remove old
listWithData.exit().remove();
// update existing
listWithData.attr('class', i => i.active ? 'active' : '');
};
update();
$('#add').click(() => {
listItems.push({
text: listItems.length+1,
active: false
});
update();
});
var toggle = (i) => {
i.active = !i.active;
update();
};
li.active {
background-color:lightblue;
}
li {
padding: 5px;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="id"></div>
<button id="add">Add</button>
</body>
</html>

Draw multiple circles using d3.js in a 3x3 format

I am trying to draw 9 circles in a 3x3 format using d3.js .
Here is my script:-
<script src="//d3js.org/d3.v3.min.js"></script>
<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
<div class="barChart"></div>
<div class="circles"></div>
<style>
</style>
<script>
$(document).ready(function () {
circles();
$(".circles").show();
function circles() {
var svg = d3.select(".circles").append("svg");
var data = ["Z","Z","Z","Z","Z","Z","Z","Z","Z"];
var groups = svg.selectAll("g")
.data(data).attr("width",100).attr("height",100)
.enter()
.append("g");
groups.attr("transform", function(d, i) {
var x = 100;
console.log(i);
var y = 50 * i + 100 ;
return "translate(" + [x,y] + ")";
});
var circles = groups.append("circle")
.attr({cx: function(d,i){
return 0;
},
cy: function(d,i){
return 0;}})
.attr("r", "20")
.attr("fill", "red")
.style("stroke-width","2px");
var label = groups.append("text")
.text(function(d){
return d;
})
.style({
"alignment-baseline": "middle",
"text-anchor": "middle",
"font-family":"Arial",
"font-size":"30",
"fill":"white"
});
}
});
But , I am just getting some half circles.
And also , I tried to have only one value in the data and tried to run the circles() in a loop but I got circles in a straight line with lot of spacing between them
for (var i = 0; i <=8 ;i++){
circles();
}
And
var groups = svg.selectAll("g")
.data("Z").attr("width",100).attr("height",100)
.enter()
.append("g");
If I follow the second method, I got circles in a straight line and with lot of spacing.
So how to get the circles like in the figure and with less spacing ?
Can anyone please help me
Your transform function is positioning your elements in a line instead of a grid. If you log out what you are translating you will see whats happening. i.e.
console.log("translate(" + [x,y] + "");
/* OUTPUTS
translate(100,100)
translate(100,150)
translate(100,200)
translate(100,250)
translate(100,300)
translate(100,350)
translate(100,400)
translate(100,450)
translate(100,500)
translate(100,100)
*/
They are being stacked one on top of the other vertically.
You can modify the transform function by changing the following lines:
var x = 100 + (50* Math.floor(i/3));
var y = 50 * (i%3) + 20 ;
Finally, the SVG container is clipping your drawing so you are seeing only half of anything below 150px.
You can modify the width as follows:
var svg = d3.select(".circles")
.append("svg")
.attr({"height": '300px'});
The simplest way to fix your code is to modify the groups transform
groups.attr("transform", function(d, i) {
var x = (i % 3) * 100 + 200; // x varies between 200 and 500
var y = 50 * Math.floor(i / 3) + 100 ; // y varies between 100 and 250
return "translate(" + [x,y] + ")";
});
Here, i will loop between 0 and 8 because you have 8 elements in your data variable, in the x assigment, i%3 is worth 0,1,2,0,1,2,0,1,2, and in the y assignement, Math.floor(i / 3) is worth 0,0,0,1,1,1,2,2,2 so you basically get a 2D grid :
0,0 1,0 2,0
1,0 1,1 2,1
2,0 2,1 2,2

d3js Moving SVG elements inside a transforming group

I am working on a query builder project. I am trying to build a query generator using d3.js. I am stucked in a part where I want to move certain elements inside a transforming group. This is the repo and I am stucked in this function. I want to move the operators after connecting it and update the connected lines. Can anyone help me?
var circleDrag = d3.behavior.drag()
.on('dragstart', function () {
d3.event.sourceEvent.stopPropagation();
})
.on('drag', function () {
var parentQboxGroupId = d3.select(this).select(function () {
return this.parentNode;
});
var grandParent = parentQboxGroupId.select(function(){
return this.parentNode;
});
var drawingGroup = d3.select('#'+grandParent.attr('id'));
var currentC = d3.select(this);
dragging = true;
drawingGroup
.select('.lineInsideQbox')
.attr('x1', currentC.attr('cx'))
.attr('y1', currentC.attr('cy'))
.style('stroke','green')
.style('stroke-width','2px');
dummyLine.src = currentC.attr('id');
console.log('CIRCLE IS BEING DRAGGED' + JSON.stringify(dummyLine));
})
.on('dragend', function () {
console.log('drag circle end');
//if(!selectedCircle.id){
// dummyLine.target = selectedQbox.id;
//}
dummyLine.target = selectedCircle.id;
dragging = false;
console.log('DRAG END : SELCTED NODE : '+ JSON.stringify(selectedCircle));
console.log('DRAG END : DUMMY LINE : '+ JSON.stringify(dummyLine));
var targetNode = d3.select('#'+dummyLine.target);
var srcNode = d3.select('#'+dummyLine.src);
console.log('split : ' + dummyLine.src.split('--'));
var group = '#' + (dummyLine.src).split('--')[1];
console.log('G: ' + group);
d3.select(group).append('line')
.attr('id', function () {
var a = (dummyLine.src).split('--');
var b = (dummyLine.target).split('--');
if( a[0]== 'nodeRight'){
return dummyLine.src + '__' + dummyLine.target;
}else{
return dummyLine.target + '__' + dummyLine.src;
}
})
.attr('class', function () {
var a = (dummyLine.src).split('--');
var b = (dummyLine.target).split('--');
return 'line '+ a[1]+' '+b[1];
})
.attr('x1', srcNode.attr('cx'))
.attr('y1',srcNode.attr('cy'))
.attr('x2',targetNode.attr('cx'))
.attr('y2',targetNode.attr('cy'))
.style('stroke', 'black')
.style('stroke-width', '3px')
;
dummyLine.src = null;
dummyLine.target = null;
});
EDIT : When I try to drop a query Box. I can drop other operators inside it. Then I should be able to connect them inside. Here is the image showing what I am trying.
After the connections made, I try yo move large box & small operators individually. That's where the code break.
The main issue is that to move the operator, you use a translate to move the whole group ( tag) which includes the image, the two circles and the line. You then set the other end of the line using CX, CY values of the other operator it is connected to.
This wont work because the CX and CY values of the circles are not updated when you perform a translate, so on a second move, it would put the x, y values at the original point of the circles, not to the moved point.
To resolve, instead of translating the whole group, translate only the image, update the cx and cy values of the circles and then update the line x, y values with the new cx, cy of the circles:
All of the amendments needed are within your operatorDrag.js file.
First of all, when you append the circles, add an attribute which holds the original cx and cy values. We will need these when calculating the new cx, cy when dragging the operator:
change from this:
var op = currGroup
.append('image')
.attr('class', 'operator')
.attr('width', elem.attr('width') * 0.75)
.attr('height', elem.attr('height') * 0.75)
.attr('x', d3.mouse(this)[0])
.attr('y', d3.mouse(this)[1])
.attr('xlink:href', elem.attr('href'));
currGroup
.append('circle')
.attr('class', 'node nodeLeft')
.attr('id', function () {
return 'nodeLeft--' + currGroup.attr('id');
})
.attr('cx', op.attr('x'))
.attr('cy', op.attr('height') / 2 + Number(op.attr('y')))
.attr('r', 5)
.style('fill', 'red')
.on('mouseover', function () {
selectedCircle = {
id: d3.select(this).attr('id'),
cls: 'nodeLeft'
}
})
.call(circleDrag)
;
currGroup
.append('circle')
.attr('class', 'node nodeRight')
.attr('id', function () {
return 'nodeRight--' + currGroup.attr('id');
})
.attr('cx', Number(op.attr('x')) + Number(op.attr('width')))
.attr('cy', op.attr('height') / 2 + Number(op.attr('y')))
.attr('r', 5)
.style('fill', 'red')
.on('mouseover', function () {
selectedCircle = {
id: d3.select(this).attr('id'),
cls: 'nodeRight'
}
})
.call(circleDrag)
;
To this (the updated code is contained in comments starting with #SB):
var op = currGroup
.append('image')
.attr('class', 'operator')
.attr('width', elem.attr('width') * 0.75)
.attr('height', elem.attr('height') * 0.75)
.attr('x', d3.mouse(this)[0])
.attr('y', d3.mouse(this)[1])
.attr('xlink:href', elem.attr('href'));
currGroup
.append('circle')
.attr('class', 'node nodeLeft')
.attr('id', function () {
return 'nodeLeft--' + currGroup.attr('id');
})
.attr('cx', op.attr('x'))
.attr('cy', op.attr('height') / 2 + Number(op.attr('y')))
// #SB: add a reference to the original cx and cy position.
// we will need it to set new cx cy when moving operator
.attr('data-cx', op.attr('x'))
.attr('data-cy', op.attr('height') / 2 + Number(op.attr('y')))
//----------------------------------------------------------------------
.attr('r', 5)
.style('fill', 'red')
.on('mouseover', function () {
selectedCircle = {
id: d3.select(this).attr('id'),
cls: 'nodeLeft'
}
})
.call(circleDrag)
;
currGroup
.append('circle')
.attr('class', 'node nodeRight')
.attr('id', function () {
return 'nodeRight--' + currGroup.attr('id');
})
.attr('cx', Number(op.attr('x')) + Number(op.attr('width')))
.attr('cy', op.attr('height') / 2 + Number(op.attr('y')))
// #SB: add a reference to the original cx and cy position.
// we will need it to set new cx cy when moving operator
.attr('data-cx', Number(op.attr('x')) + Number(op.attr('width')))
.attr('data-cy', op.attr('height') / 2 + Number(op.attr('y')))
//----------------------------------------------------------------------
.attr('r', 5)
.style('fill', 'red')
.on('mouseover', function () {
selectedCircle = {
id: d3.select(this).attr('id'),
cls: 'nodeRight'
}
})
.call(circleDrag)
;
Once you have done this, go to your on drag method for the operators. This is the code we are going to change:
.on('drag', function () {
var g = d3.select(this);
var currentOp = g.select('.operator');
var parent = g.select(function () {
return this.parentNode;
}).select('.qbox');
var dx = d3.event.x;
var dy = d3.event.y;
var mouse = {dx: d3.event.x, dy: d3.event.y};
var currentObj = {
x: currentOp.attr('x'),
y: currentOp.attr('y'),
width: currentOp.attr('width'),
height: currentOp.attr('height')
};
var parentObj = {
x: parent.attr('x'),
y: parent.attr('y'),
width: parent.attr('width'),
height: parent.attr('height')
};
//console.log('parent width : ' + parent.attr('width'));
//console.log('parent width : ' + currentOp.attr('width'));
//g.attr('transform', 'translate(' + x + ',' + y + ')');
var loc = getXY(mouse, currentObj, parentObj);
g.attr('transform', 'translate(' + loc.x + ',' + loc.y + ')');
d3.select('#' + g.attr('id')).selectAll('.line')[0].forEach(function (e1) {
var line = d3.select(e1);
console.log('-------------------');
console.log('line : ' + line.attr('id'));
console.log('-------------------');
var split = line.attr('id').split('__');
if(g.attr('id') == split[0]){
//change x2, y2
var otherNode = d3.select('#'+split[1]);
line.attr('x2', otherNode.attr('cx'));
line.attr('y2', otherNode.attr('cy'));
}else{
var otherNode = d3.select('#'+split[0]);
line.attr('x1', otherNode.attr('cx'));
line.attr('y1', otherNode.attr('cy'));
}
})
}))
First thing is, do not translate the whole object, only the image:
var g = d3.select(this);
var currentOp = g.select('.operator');
var parent = g.select(function () {
return this.parentNode;
}).select('.qbox');
//#SB: added a reference to the parent id
var parent_id = g.select(function () {
return this.parentNode;
}).attr('id');
//---------------------------------------
var dx = d3.event.x;
var dy = d3.event.y;
var mouse = {dx: d3.event.x, dy: d3.event.y};
var currentObj = {
x: currentOp.attr('x'),
y: currentOp.attr('y'),
width: currentOp.attr('width'),
height: currentOp.attr('height')
};
var parentObj = {
x: parent.attr('x'),
y: parent.attr('y'),
width: parent.attr('width'),
height: parent.attr('height')
};
var loc = getXY(mouse, currentObj, parentObj);
//#SB: Do not translate everything, the cx, cy values of the circle are not updated
// when translating which will make future moves calculate incorrectly
g.selectAll('image').attr('transform', 'translate(' + loc.x + ',' + loc.y + ')');
Then, instead of translating the circles, change their cx, and cy values using the original cx, cy and translate values:
g.selectAll('circle')
.attr('cx', function () {
return parseFloat(d3.select(this).attr('data-cx')) + parseFloat(loc.x);
})
.attr('cy', function () {
return parseFloat(d3.select(this).attr('data-cy')) + parseFloat(loc.y);
});
The last thing is the update to the lines. In your original code, you were selecting all lines within the operator group but you will actually miss some lines by only selecting this group. Some lines can be a part of another operator group but be connected to the operator that is moving.
In this case we should select all lines within the parent group and check if the line is connected to the operator we are moving.
If it is connected then we update the x and y values:
//#SB: Select all the lines in the parent group instead of only group of the
// operator we are moving. There can be lines that exists on other groups that
// do not exist within the group that is being moved.
d3.select('#' + parent_id).selectAll('.line')[0].forEach(function (el) {
var parent_id = g.attr('id')
var line = d3.select(el)
var nodeType = line.attr('id').split("__"); // id tells us if the line is connected to the left or right node
var operators = line.attr('class').split(" "); // class holds info on what operators the line is connected to
var sourceCircleId = nodeType[0].split("--")[0] + '--' + operators[1];
var targetCircleId = nodeType[1].split("--")[0] + '--' + operators[2];
if (parent_id == operators[1] || parent_id == operators[2]) { // the line is connected to the operator we are moving
line.attr('x1', d3.select('#' + sourceCircleId).attr('cx'))
line.attr('y1', d3.select('#' + sourceCircleId).attr('cy'))
line.attr('x2', d3.select('#' + targetCircleId).attr('cx'))
line.attr('y2', d3.select('#' + targetCircleId).attr('cy'))
}
});
Complete OnDrag code:
.on('drag', function () {
var g = d3.select(this);
var currentOp = g.select('.operator');
var parent = g.select(function () {
return this.parentNode;
}).select('.qbox');
//#SB: added a reference to the parent id
var parent_id = g.select(function () {
return this.parentNode;
}).attr('id');
//---------------------------------------
var dx = d3.event.x;
var dy = d3.event.y;
var mouse = {dx: d3.event.x, dy: d3.event.y};
var currentObj = {
x: currentOp.attr('x'),
y: currentOp.attr('y'),
width: currentOp.attr('width'),
height: currentOp.attr('height')
};
var parentObj = {
x: parent.attr('x'),
y: parent.attr('y'),
width: parent.attr('width'),
height: parent.attr('height')
};
var loc = getXY(mouse, currentObj, parentObj);
//#SB: Do not translate everything, the cx, cy values of the circle are not updated
// when translating which will make future moves calculate incorrectly
g.selectAll('image').attr('transform', 'translate(' + loc.x + ',' + loc.y + ')');
g.selectAll('circle')
.attr('cx', function () {
return parseFloat(d3.select(this).attr('data-cx')) + parseFloat(loc.x);
})
.attr('cy', function () {
return parseFloat(d3.select(this).attr('data-cy')) + parseFloat(loc.y);
});
//#SB: Select all the lines in the parent group instead of only group of the
// operator we are moving. There can be lines that exists on other groups that
// do not exist within the group that is being moved.
d3.select('#' + parent_id).selectAll('.line')[0].forEach(function (el) {
var parent_id = g.attr('id')
var line = d3.select(el)
var nodeType = line.attr('id').split("__"); // id tells us if the line is connected to the left or right node
var operators = line.attr('class').split(" "); // class holds info on what operators the line is connected to
var sourceCircleId = nodeType[0].split("--")[0] + '--' + operators[1];
var targetCircleId = nodeType[1].split("--")[0] + '--' + operators[2];
if (parent_id == operators[1] || parent_id == operators[2]) { // the line is connected to the operator we are moving
line.attr('x1', d3.select('#' + sourceCircleId).attr('cx'))
line.attr('y1', d3.select('#' + sourceCircleId).attr('cy'))
line.attr('x2', d3.select('#' + targetCircleId).attr('cx'))
line.attr('y2', d3.select('#' + targetCircleId).attr('cy'))
}
});
}))

Categories