D3 Variable Colors and Widths (SO)
by Joel Lubrano
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<div id="foo"></div>
JavaScript
// Taken from http://bl.ocks.org/mbostock/4163057
var points = [
[25, 100],
[260, 13],
[260, 149],
[31, 24]
];
var width = 320,
height = 150;
// var color = d3.interpolateLab("#008000", "#c83a22");
// custom color function
var color = function(idx) {
switch(idx % 4) {
case 0: return 'red';
case 1: return 'blue';
case 2: return 'yellow';
case 3: return 'black';
};
};
var strokeWidth = function() {
// a random number between 1 and 5.
return Math.ceil(Math.random() * 10);
};
var svg = d3.select("#foo").append("svg")
.attr("width", width)
.attr("height", height);
var line = d3.svg.line()
.interpolate("basis");
svg.selectAll("path")
.data(quad(sample(line(points), 8)))
.enter().append("path")
.style("fill", function(d, i) { return color(i); })
.style("stroke", function(d, i) { return color(i); })
.style("stroke-width", strokeWidth)
.attr("d", function(d) { return lineJoin(d[0], d[1], d[2], d[3], 32); });
// Sample the SVG path string "d" uniformly with the specified precision.
function sample(d, precision) {
var path = document.createElementNS(d3.ns.prefix.svg, "path");
path.setAttribute("d", d);
var n = path.getTotalLength(), t = [0], i = 0, dt = precision;
while ((i += dt) < n) t.push(i);
t.push(n);
return t.map(function(t) {
var p = path.getPointAtLength(t), a = [p.x, p.y];
a.t = t / n;
return a;
});
}
// Compute quads of adjacent points [p0, p1, p2, p3].
function quad(points) {
return d3.range(points.length - 1).map(function(i) {
var a = [points[i - 1], points[i], points[i + 1], points[i + 2]];
a.t = (points[i].t + points[i + 1].t) / 2;
return a;
});
}
// Compute stroke outline for segment p12.
function lineJoin(p0, p1, p2, p3, width) {
var u12 = perp(p1, p2),
r = width / 2,
a = [p1[0] + u12[0] * r, p1[1] + u12[1] * r],
b = [p2[0] + u12[0] * r, p2[1] + u12[1] * r],
c = [p2[0] - u12[0] * r, p2[1]...