Skip to content

Instantly share code, notes, and snippets.

@micahstubbs
Last active January 2, 2017 20:24
Show Gist options
  • Save micahstubbs/3fa3c1a523c8f3c2cfb9 to your computer and use it in GitHub Desktop.
Save micahstubbs/3fa3c1a523c8f3c2cfb9 to your computer and use it in GitHub Desktop.
Sankey Particles with only inline styles
license: CC0-1.0

Sankey Particles with only inline styles. A fork of the bl.ock Sankey Particles III from emeeks

Since it doesn't appear possible to set CSS pseudo-class rules from JavaScript we'll bind mouseover and mouseout events to each link path to replicate the functionality of the :hover CSS psuedo-class.

.link:hover {
  stroke-opacity: .25;
}

becomes

link
    .on('mouseover', function() {
      d3.select(this).style("stroke-opacity", .25);
    })
    .on('mouseout', function() {
      d3.select(this).style("stroke-opacity", .15);
    });

all other styles can be converted to inline styles more directly, like:

.link {
  fill: none;
  stroke: #000;
  stroke-opacity: .15;
}

to

var link = svg.append("g").selectAll(".link")
    /* ... */
    .style({
      "fill": "none",
      "stroke": "#000",
      "stroke-opacity": .15
    })

Original README.md:

Using particles to indicate flow between reservoirs in a sankey diagram. This time with particles moving at varying speeds and maintaining the color of the source node. You can drag the reservoirs (the rectangles) to adjust the path of the flows.

Other examples of sankeys with particles:

d3.sankey = function() {
var sankey = {},
nodeWidth = 24,
nodePadding = 8,
size = [1, 1],
nodes = [],
links = [];
sankey.nodeWidth = function(_) {
if (!arguments.length) return nodeWidth;
nodeWidth = +_;
return sankey;
};
sankey.nodePadding = function(_) {
if (!arguments.length) return nodePadding;
nodePadding = +_;
return sankey;
};
sankey.nodes = function(_) {
if (!arguments.length) return nodes;
nodes = _;
return sankey;
};
sankey.links = function(_) {
if (!arguments.length) return links;
links = _;
return sankey;
};
sankey.size = function(_) {
if (!arguments.length) return size;
size = _;
return sankey;
};
sankey.layout = function(iterations) {
computeNodeLinks();
computeNodeValues();
computeNodeBreadths();
computeNodeDepths(iterations);
computeLinkDepths();
return sankey;
};
sankey.relayout = function() {
computeLinkDepths();
return sankey;
};
sankey.link = function() {
var curvature = .5;
function link(d) {
var x0 = d.source.x + d.source.dx,
x1 = d.target.x,
xi = d3.interpolateNumber(x0, x1),
x2 = xi(curvature),
x3 = xi(1 - curvature),
y0 = d.source.y + d.sy + d.dy / 2,
y1 = d.target.y + d.ty + d.dy / 2;
return "M" + x0 + "," + y0
+ "C" + x2 + "," + y0
+ " " + x3 + "," + y1
+ " " + x1 + "," + y1;
}
link.curvature = function(_) {
if (!arguments.length) return curvature;
curvature = +_;
return link;
};
return link;
};
// Populate the sourceLinks and targetLinks for each node.
// Also, if the source and target are not objects, assume they are indices.
function computeNodeLinks() {
nodes.forEach(function(node) {
node.sourceLinks = [];
node.targetLinks = [];
});
links.forEach(function(link) {
var source = link.source,
target = link.target;
if (typeof source === "number") source = link.source = nodes[link.source];
if (typeof target === "number") target = link.target = nodes[link.target];
source.sourceLinks.push(link);
target.targetLinks.push(link);
});
}
// Compute the value (size) of each node by summing the associated links.
function computeNodeValues() {
nodes.forEach(function(node) {
node.value = Math.max(
d3.sum(node.sourceLinks, value),
d3.sum(node.targetLinks, value)
);
});
}
// Iteratively assign the breadth (x-position) for each node.
// Nodes are assigned the maximum breadth of incoming neighbors plus one;
// nodes with no incoming links are assigned breadth zero, while
// nodes with no outgoing links are assigned the maximum breadth.
function computeNodeBreadths() {
var remainingNodes = nodes,
nextNodes,
x = 0;
while (remainingNodes.length) {
nextNodes = [];
remainingNodes.forEach(function(node) {
node.x = x;
node.dx = nodeWidth;
node.sourceLinks.forEach(function(link) {
if (nextNodes.indexOf(link.target) < 0) {
nextNodes.push(link.target);
}
});
});
remainingNodes = nextNodes;
++x;
}
//
moveSinksRight(x);
scaleNodeBreadths((size[0] - nodeWidth) / (x - 1));
}
function moveSourcesRight() {
nodes.forEach(function(node) {
if (!node.targetLinks.length) {
node.x = d3.min(node.sourceLinks, function(d) { return d.target.x; }) - 1;
}
});
}
function moveSinksRight(x) {
nodes.forEach(function(node) {
if (!node.sourceLinks.length) {
node.x = x - 1;
}
});
}
function scaleNodeBreadths(kx) {
nodes.forEach(function(node) {
node.x *= kx;
});
}
function computeNodeDepths(iterations) {
var nodesByBreadth = d3.nest()
.key(function(d) { return d.x; })
.sortKeys(d3.ascending)
.entries(nodes)
.map(function(d) { return d.values; });
//
initializeNodeDepth();
resolveCollisions();
for (var alpha = 1; iterations > 0; --iterations) {
relaxRightToLeft(alpha *= .99);
resolveCollisions();
relaxLeftToRight(alpha);
resolveCollisions();
}
function initializeNodeDepth() {
var ky = d3.min(nodesByBreadth, function(nodes) {
return (size[1] - (nodes.length - 1) * nodePadding) / d3.sum(nodes, value);
});
nodesByBreadth.forEach(function(nodes) {
nodes.forEach(function(node, i) {
node.y = i;
node.dy = node.value * ky;
});
});
links.forEach(function(link) {
link.dy = link.value * ky;
});
}
function relaxLeftToRight(alpha) {
nodesByBreadth.forEach(function(nodes, breadth) {
nodes.forEach(function(node) {
if (node.targetLinks.length) {
var y = d3.sum(node.targetLinks, weightedSource) / d3.sum(node.targetLinks, value);
node.y += (y - center(node)) * alpha;
}
});
});
function weightedSource(link) {
return center(link.source) * link.value;
}
}
function relaxRightToLeft(alpha) {
nodesByBreadth.slice().reverse().forEach(function(nodes) {
nodes.forEach(function(node) {
if (node.sourceLinks.length) {
var y = d3.sum(node.sourceLinks, weightedTarget) / d3.sum(node.sourceLinks, value);
node.y += (y - center(node)) * alpha;
}
});
});
function weightedTarget(link) {
return center(link.target) * link.value;
}
}
function resolveCollisions() {
nodesByBreadth.forEach(function(nodes) {
var node,
dy,
y0 = 0,
n = nodes.length,
i;
// Push any overlapping nodes down.
nodes.sort(ascendingDepth);
for (i = 0; i < n; ++i) {
node = nodes[i];
dy = y0 - node.y;
if (dy > 0) node.y += dy;
y0 = node.y + node.dy + nodePadding;
}
// If the bottommost node goes outside the bounds, push it back up.
dy = y0 - nodePadding - size[1];
if (dy > 0) {
y0 = node.y -= dy;
// Push any overlapping nodes back up.
for (i = n - 2; i >= 0; --i) {
node = nodes[i];
dy = node.y + node.dy + nodePadding - y0;
if (dy > 0) node.y -= dy;
y0 = node.y;
}
}
});
}
function ascendingDepth(a, b) {
return a.y - b.y;
}
}
function computeLinkDepths() {
nodes.forEach(function(node) {
node.sourceLinks.sort(ascendingTargetDepth);
node.targetLinks.sort(ascendingSourceDepth);
});
nodes.forEach(function(node) {
var sy = 0, ty = 0;
node.sourceLinks.forEach(function(link) {
link.sy = sy;
sy += link.dy;
});
node.targetLinks.forEach(function(link) {
link.ty = ty;
ty += link.dy;
});
});
function ascendingSourceDepth(a, b) {
return a.source.y - b.source.y;
}
function ascendingTargetDepth(a, b) {
return a.target.y - b.target.y;
}
}
function center(node) {
return node.y + node.dy / 2;
}
function value(link) {
return link.value;
}
return sankey;
};
{
"nodes":[
{
"name":"Agricultural 'waste'",
"depth": 0
},
{
"name":"Bio-conversion",
"depth": 1
},
{
"name":"Liquid",
"depth": 2
},
{
"name":"Losses",
"depth": 7
},
{
"name":"Solid",
"depth": 2
},
{
"name":"Gas",
"depth": 2
},
{
"name":"Biofuel imports",
"depth": 0
},
{
"name":"Biomass imports",
"depth": 0
},
{
"name":"Coal imports",
"depth": 0
},
{
"name":"Coal",
"depth": 1
},
{
"name":"Coal reserves",
"depth": 0
},
{
"name":"District heating",
"depth": 4
},
{
"name":"Industry",
"depth": 7
},
{
"name":"Heating and cooling - commercial",
"depth": 7
},
{
"name":"Heating and cooling - homes",
"depth": 7
},
{
"name":"Electricity grid",
"depth": 4
},
{
"name":"Over generation / exports",
"depth": 7
},
{
"name":"H2 conversion",
"depth": 5
},
{
"name":"Road transport",
"depth": 7
},
{
"name":"Agriculture",
"depth": 7
},
{
"name":"Rail transport",
"depth": 7
},
{
"name":"Lighting & appliances - commercial",
"depth": 7
},
{
"name":"Lighting & appliances - homes",
"depth": 7
},
{
"name":"Gas imports",
"depth": 0
},
{
"name":"Ngas",
"depth": 1
},
{
"name":"Gas reserves",
"depth": 0
},
{
"name":"Thermal generation",
"depth": 3
},
{
"name":"Geothermal",
"depth": 0
},
{
"name":"H2",
"depth": 6
},
{
"name":"Hydro",
"depth": 0
},
{
"name":"International shipping",
"depth": 7
},
{
"name":"Domestic aviation",
"depth": 7
},
{
"name":"International aviation",
"depth": 7
},
{
"name":"National navigation",
"depth": 7
},
{
"name":"Marine algae",
"depth": 0
},
{
"name":"Nuclear",
"depth": 0
},
{
"name":"Oil imports",
"depth": 0
},
{
"name":"Oil",
"depth": 1
},
{
"name":"Oil reserves",
"depth": 0
},
{
"name":"Other waste",
"depth": 0
},
{
"name":"Pumped heat",
"depth": 0
},
{
"name":"Solar PV",
"depth": 1
},
{
"name":"Solar Thermal",
"depth": 1
},
{
"name":"Solar",
"depth": 0
},
{
"name":"Tidal",
"depth": 0
},
{
"name":"UK land based bioenergy",
"depth": 0
},
{
"name":"Wave",
"depth": 0
},
{
"name":"Wind",
"depth": 0
}
],
"links":[
{
"source":0,
"target":1,
"value":124.729
},
{
"source":1,
"target":2,
"value":0.597
},
{
"source":1,
"target":3,
"value":26.862
},
{
"source":1,
"target":4,
"value":280.322
},
{
"source":1,
"target":5,
"value":81.144
},
{
"source":6,
"target":2,
"value":35
},
{
"source":7,
"target":4,
"value":35
},
{
"source":8,
"target":9,
"value":11.606
},
{
"source":10,
"target":9,
"value":63.965
},
{
"source":9,
"target":4,
"value":75.571
},
{
"source":11,
"target":12,
"value":10.639
},
{
"source":11,
"target":13,
"value":22.505
},
{
"source":11,
"target":14,
"value":46.184
},
{
"source":15,
"target":16,
"value":104.453
},
{
"source":15,
"target":14,
"value":113.726
},
{
"source":15,
"target":17,
"value":27.14
},
{
"source":15,
"target":12,
"value":342.165
},
{
"source":15,
"target":18,
"value":37.797
},
{
"source":15,
"target":19,
"value":4.412
},
{
"source":15,
"target":13,
"value":40.858
},
{
"source":15,
"target":3,
"value":56.691
},
{
"source":15,
"target":20,
"value":7.863
},
{
"source":15,
"target":21,
"value":90.008
},
{
"source":15,
"target":22,
"value":93.494
},
{
"source":23,
"target":24,
"value":40.719
},
{
"source":25,
"target":24,
"value":82.233
},
{
"source":5,
"target":13,
"value":0.129
},
{
"source":5,
"target":3,
"value":1.401
},
{
"source":5,
"target":26,
"value":151.891
},
{
"source":5,
"target":19,
"value":2.096
},
{
"source":5,
"target":12,
"value":48.58
},
{
"source":27,
"target":15,
"value":7.013
},
{
"source":17,
"target":28,
"value":20.897
},
{
"source":17,
"target":3,
"value":6.242
},
{
"source":28,
"target":18,
"value":20.897
},
{
"source":29,
"target":15,
"value":6.995
},
{
"source":2,
"target":12,
"value":121.066
},
{
"source":2,
"target":30,
"value":128.69
},
{
"source":2,
"target":18,
"value":135.835
},
{
"source":2,
"target":31,
"value":14.458
},
{
"source":2,
"target":32,
"value":206.267
},
{
"source":2,
"target":19,
"value":3.64
},
{
"source":2,
"target":33,
"value":33.218
},
{
"source":2,
"target":20,
"value":4.413
},
{
"source":34,
"target":1,
"value":4.375
},
{
"source":24,
"target":5,
"value":122.952
},
{
"source":35,
"target":26,
"value":839.978
},
{
"source":36,
"target":37,
"value":504.287
},
{
"source":38,
"target":37,
"value":107.703
},
{
"source":37,
"target":2,
"value":611.99
},
{
"source":39,
"target":4,
"value":56.587
},
{
"source":39,
"target":1,
"value":77.81
},
{
"source":40,
"target":14,
"value":193.026
},
{
"source":40,
"target":13,
"value":70.672
},
{
"source":41,
"target":15,
"value":59.901
},
{
"source":42,
"target":14,
"value":19.263
},
{
"source":43,
"target":42,
"value":19.263
},
{
"source":43,
"target":41,
"value":59.901
},
{
"source":4,
"target":19,
"value":0.882
},
{
"source":4,
"target":26,
"value":400.12
},
{
"source":4,
"target":12,
"value":46.477
},
{
"source":26,
"target":15,
"value":525.531
},
{
"source":26,
"target":3,
"value":787.129
},
{
"source":26,
"target":11,
"value":79.329
},
{
"source":44,
"target":15,
"value":9.452
},
{
"source":45,
"target":1,
"value":182.01
},
{
"source":46,
"target":15,
"value":19.013
},
{
"source":47,
"target":15,
"value":289.366
}
]
}
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Sankey Particles</title>
</head>
<body>
<canvas width='1000' height='1000' ></canvas>
<svg width='1000' height='1000' ></svg>
<script src='https://d3js.org/d3.v3.min.js' charset='utf-8' type='text/javascript'></script>
<script src='d3.sankey.js' charset='utf-8' type='text/javascript'></script>
<script type='text/javascript'>
var canvas = d3.select('canvas')
.style('position', 'absolute');
var margin = {top: 1, right: 1, bottom: 6, left: 1},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom,
nodeWidth = 15;
var formatNumber = d3.format(',.0f'),
format = function(d) { return formatNumber(d) + ' TWh'; },
color = d3.scale.category20();
var svg = d3.select('svg')
.style('position', 'absolute')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
var sankey = d3.sankey()
.nodeWidth(nodeWidth)
.nodePadding(10)
.size([width, height]);
var path = sankey.link();
var freqCounter = 1;
d3.json('energy.json', function(data) {
var graph = calculateNodeDepth(data);
var maxDepth = d3.max(graph.nodes.map(function(d) { return d.depth; }));
console.log('maxDepth', maxDepth);
sankey
.nodes(graph.nodes)
.links(graph.links)
.layout(32);
console.log('graph.nodes', graph.nodes);
var link = svg.append('g').selectAll('.link')
.data(graph.links)
.enter().append('path')
.attr('class', 'link')
.attr('id', function(d) {
return 'pathTo' + d.target.id;
})
.attr('d', path)
.style('stroke-width', function(d) { return Math.max(1, d.dy); })
.style({
'fill': 'none',
'stroke': '#000',
'stroke-opacity': .15
})
.sort(function(a, b) { return b.dy - a.dy; });
link
.on('mouseover', function() {
d3.select(this).style('stroke-opacity', .25);
})
.on('mouseout', function() {
d3.select(this).style('stroke-opacity', .15);
});
link.append('title')
.text(function(d) { return d.target.name + ' → ' + d.target.name + '\n' + format(d.value); });
var node = svg.append('g').selectAll('.node')
.data(graph.nodes)
.enter().append('g')
.attr('class', 'node')
.attr('transform', function(d) { return 'translate(' + d.x + ',' + d.y + ')'; })
.call(d3.behavior.drag()
.origin(function(d) { return d; })
.on('dragstart', function() { this.parentNode.appendChild(this); })
.on('drag', dragmove));
node.append('rect')
.attr('height', function(d) { return d.dy; })
.attr('width', sankey.nodeWidth())
.style('fill', function(d) { return d.color = color(d.name.replace(/ .*/, '')); })
.style({
'stroke': 'none',
'cursor': 'move',
'fill-opacity': .9,
'shape-rendering': 'crispEdges'
})
.append('title')
.text(function(d) { return d.name + '\n' + format(d.value); });
// draw nice curved text for links
var pathTotalLength;
var nameOffset;
var nodeNamesDrawn = {};
var maxWidth = (width / maxDepth) - nodeWidth*1.2;
console.log('maxWidth', maxWidth);
var linkText = svg.append('text')
.attr('x', 0)
.attr('dy', '.35em')
.style('pointer-events', 'none');
svg.selectAll('.link')
.each(function(d) {
switch (d.depth) {
case 7:
pathTotalLength = d3.select('#pathTo' + d.target.id)[0][0].getTotalLength();
// console.log('pathTotalLength', pathTotalLength);
textSize = getTextSize(d.target.name);
nameOffsetStart = pathTotalLength - textSize.width - 3;
nameOffsetEnd = textSize.width;
// console.log('nameOffsetStart', nameOffsetStart);
// this works for leaf nodes
// if we haven't already drawn a node name, draw it
if (!nodeNamesDrawn.hasOwnProperty(d.target.id)) {
console.log('linkText', linkText);
linkText.append('textPath')
.attr('xlink:href', '#pathTo' + d.target.id)
.attr('id', '#nameTextPathTo' + d.target.id)
.attr('startOffset', nameOffsetStart)
.attr('text-anchor', 'start')
.text(d.target.name)
/*.filter(function() {
var textPathId = d3.select(this)[0][0].id;
var targetNodeId = Number(textPathId.replace(/#nameTextPathTo/, ''));
var targetNodeDepth = graph.nodes[targetNodeId].depth;
// console.log('textPathId', textPathId);
console.log(graph.nodes[targetNodeId].name);
console.log('targetNodeId', targetNodeId);
console.log('targetNodeDepth', targetNodeDepth);
return targetNodeDepth < 7;
})
.attr('startOffset', nameOffsetEnd)
.attr('text-anchor', 'end');
*/
nodeNamesDrawn[d.target.id] = d.target.name;
}
break;
default:
pathTotalLength = d3.select('#pathTo' + d.target.id)[0][0].getTotalLength();
// console.log('pathTotalLength', pathTotalLength);
textSize = getTextSize(d.target.name);
nameOffsetStart = pathTotalLength - textSize.width - 3;
nameOffsetEnd = textSize.width;
// console.log('nameOffsetStart', nameOffsetStart);
// this works for leaf nodes
// if we haven't already drawn a node name, draw it
if (!nodeNamesDrawn.hasOwnProperty(d.target.id)) {
console.log('linkText', linkText);
linkText.append('textPath')
.attr('xlink:href', '#pathTo' + d.target.id)
.attr('id', '#nameTextPathTo' + d.target.id)
.attr('startOffset', nameOffsetStart)
.attr('text-anchor', 'start')
.text(d.target.name)
nodeNamesDrawn[d.target.id] = d.target.name;
}
break;
}
// draw link labels
linkText.append('textPath')
.attr('xlink:href', '#pathTo' + d.target.id)
.attr('startOffset', 3)
.text(d.label);
})
// draw linear text for nodes
/*
node.append('text')
.attr('x', -6)
.attr('y', function(d) { return d.dy / 2; })
.attr('dy', '.35em')
.attr('text-anchor', 'end')
.attr('transform', null)
.style({
'pointer-events': 'none',
'text-shadow': '0 1px 0 #fff'
})
.text(function(d) { return d.name; })
.filter(function(d) { return d.x < width / 2; })
.attr('x', 6 + sankey.nodeWidth())
.attr('text-anchor', 'start');
*/
function dragmove(d) {
d3.select(this).attr('transform', 'translate(' + d.x + ',' + (d.y = Math.max(0, Math.min(height - d.dy, d3.event.y))) + ')');
sankey.relayout();
link.attr('d', path);
}
var linkExtent = d3.extent(graph.links, function (d) {return d.value});
var frequencyScale = d3.scale.linear().domain(linkExtent).range([0.05,1]);
var particleSize = d3.scale.linear().domain(linkExtent).range([1,5]);
graph.links.forEach(function (link) {
link.freq = frequencyScale(link.value);
link.particleSize = 2;
link.particleColor = d3.scale.linear().domain([0,1])
.range([link.target.color, link.target.color]);
})
var t = d3.timer(tick, 1000);
var particles = [];
function tick(elapsed, time) {
particles = particles.filter(function (d) {return d.current < d.path.getTotalLength()});
d3.selectAll('path.link')
.each(
function (d) {
// if (d.freq < 1) {
for (var x = 0;x<2;x++) {
var offset = (Math.random() - .5) * (d.dy - 4);
if (Math.random() < d.freq) {
var length = this.getTotalLength();
particles.push({link: d, time: elapsed, offset: offset, path: this, length: length, animateTime: length, speed: 0.5 + (Math.random())})
}
}
// }
/* else {
for (var x = 0; x<d.freq; x++) {
var offset = (Math.random() - .5) * d.dy;
particles.push({link: d, time: elapsed, offset: offset, path: this})
}
} */
});
particleEdgeCanvasPath(elapsed);
}
function particleEdgeCanvasPath(elapsed) {
var context = d3.select('canvas').node().getContext('2d')
context.clearRect(0,0,1000,1000);
context.fillStyle = 'gray';
context.lineWidth = '1px';
for (var x in particles) {
var currentTime = elapsed - particles[x].time;
// var currentPercent = currentTime / 1000 * particles[x].path.getTotalLength();
particles[x].current = currentTime * 0.15 * particles[x].speed;
var currentPos = particles[x].path.getPointAtLength(particles[x].current);
context.beginPath();
context.fillStyle = particles[x].link.particleColor(0);
context.arc(currentPos.x,currentPos.y + particles[x].offset,particles[x].link.particleSize,0,2*Math.PI);
context.fill();
}
}
function calculateNodeDepth(graph) {
var inputGraph = clone(graph);
// add an id to each node
// if it does not already have one
inputGraph.nodes.forEach(function(d, i) {
if(typeof d.id === 'undefined') d.id = i;
})
var treeData = clone(inputGraph);
var treeLinks = treeData.links;
var nodesByName = {};
treeLinks.forEach(function(link) {
var parent = link.target = getNodesByName(link.target);
var child = link.target = getNodesByName(link.target);
if (parent.children) parent.children.push(child);
else parent.children = [child];
})
// Extract the root node
var root = treeLinks[0].target;
var tree = d3.layout.tree();
var nodes2 = tree.nodes(root);
// console.log('nodes2', nodes2);
// take the calculated depth and append it to
// each node in our original nodelist
inputGraph.nodes.forEach(function(d) {
if (typeof d.depth === 'undefined') {
d.depth = nodes2[d.id].depth;
}
})
return inputGraph;
function getNodesByName(name) {
return nodesByName[name] || (nodesByName[name] = {name: name});
}
}
function clone(obj) {
var copy;
// Handle the 3 simple types, and null or undefined
if (null == obj || 'object' != typeof obj) return obj;
// Handle Date
if (obj instanceof Date) {
copy = new Date();
copy.setTime(obj.getTime());
return copy;
}
// Handle Array
if (obj instanceof Array) {
copy = [];
for (var i = 0, len = obj.length; i < len; i++) {
copy[i] = clone(obj[i]);
}
return copy;
}
// Handle Object
if (obj instanceof Object) {
copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
}
return copy;
}
throw new Error("Unable to copy obj! Its type isn't supported.");
}
function getElement() {
var element = d3.select('text-size svg g');
if (element.empty()) {
element = d3.select('body')
.append('div')
.style({
width: 0,
height: 0,
position: 'absolute',
left: '-20000px',
top: '-20000px'
})
.attr('id', 'text-size')
.append('svg')
.append('g');
}
return element;
}
function getTextSize(text, style) {
if (typeof text === 'undefined') text = ["this is a test"];
if (Object.prototype.toString.call(text) !== '[object Array]') text = [text];
var maxHeight = 0;
var maxWidth = 0;
getElement().selectAll('text.measure').data(text)
.enter()
.append('text')
.text(String)
.style(style)
.style('display', 'block')
.each(function() {
var b = this.getBBox();
if (b.height > maxHeight) maxHeight = b.height;
if (b.width > maxWidth) maxWidth = b.width;
}).remove();
return {
height: maxHeight,
width: maxWidth
}
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment