Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add borders to SVG path d3 javascript

I want to have my svg paths (lines) have borders such that outlines are black, but the inside is another color. Line code:

self.lineFunction = function(dat) {
  var self = this
  var line = d3.svg.line().interpolate('linear');

  var data = dat.map(function(d) {
    return [self.xScale(d[0]), self.yScale(d[1].mean)];
  });

  return line(data);
}

self.lines = self.svg.selectAll('.line')
  .data(d3.keys(self.data), function(d) {return d})
  .enter()
  .append('path')
  .attr('d', function(d) {return self.lineFunction(self.data[d])})
  .attr('class', 'line')
  .style('stroke', 'blue')
  .style('stroke-width', '2')
  .style('fill', 'none');
like image 990
mike Avatar asked Dec 01 '22 02:12

mike


2 Answers

A forward-looking answer: if SVG2 was supported you could use the paint-order property (assuming the fill is opaque):

.pathWithBorder {
  paint-order: stroke fill;
  stroke-width: 1.8;
  stroke: black;
  fill: blue;
}

Then there's no need to duplicate the path element, and the stroke will only be visible outside the shape.

like image 64
Erik Dahlström Avatar answered Dec 02 '22 17:12

Erik Dahlström


You have to create a slightly thinner line along the same path:

inner = self.svg
  .selectAll('.inner')
  .data(d3.keys(self.data), function(d) { return d; })
  .enter().append('path')
  .attr('d', function(d) {return self.lineFunction(self.data[d])})
  .attr('class', 'inner')
  .style('stroke', 'black')
  .style('stroke-width', '1.8')
  .style('fill', 'none');

This means you have two lines on top on one another, the lower one slightly protruding from the other, giving the impression of a border.

like image 44
Jivings Avatar answered Dec 02 '22 16:12

Jivings