VividD
VividD

Reputation: 10536

Drawing three intertwined circles with D3

How to draw this:

enter image description here

with D3?

(I know the complicated answer that requires drawing all arc-like subparts separately, but is there a simpler solution? The simplest wins.)

Upvotes: 3

Views: 251

Answers (1)

DavidDomain
DavidDomain

Reputation: 15303

Not sure if this is the simplest solution, but you basically just need a bunch of circles.

Well actually just three circles in your data-set.

Adding a defs element defining masks and a clip-path will make sure that the circles intercept like they do in your image.

Just take a look at the example and you will get the idea. This is probably not the most elegant solution, but it works.

var margin        = { top: 0, right: 0, bottom: 0, left: 0}, 
    w             = 480 - margin.left - margin.right,
    h             = 480 - margin.top - margin.bottom,
    circleRadii   = 100,
    circleData    = [{x: 160, y: 160, c: "lawngreen"}, {x: 260, y: 200, c: "fuchsia"}, {x: 190, y: 260, c: "blue"}];

var svg = d3.select("body")
.append("svg")
.attr("width", w + margin.left + margin.right)
.attr("height", h + margin.left + margin.right);

var mask = svg.append("defs")
.selectAll("mask")
.data(circleData)
.enter()
.append("mask")
.attr("id", function(d,i) { return "circle_" + i});

mask
.append("circle")
.attr("cx", function (d) { return d.x; })
.attr("cy", function (d) { return d.y; })
.attr("r", circleRadii)
.attr("fill", "white");
mask
.append("circle")
.attr("cx", function (d) { return d.x; })
.attr("cy", function (d) { return d.y; })
.attr("r", circleRadii - 30)
.attr("fill", "black");

var clip = svg.select("defs")		
.append("clipPath")
.attr("id", "clip-last-circle");

clip.append("circle")
.attr("cx", circleData[1].x)
.attr("cy", circleData[1].y)
.attr("r", circleRadii - 30);

clip.append("circle")
.attr("cx", circleData[1].x/4)
.attr("cy", circleData[1].y)
.attr("r", circleRadii);

var group = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var circles = group.selectAll("circle")
.data(circleData)
.enter()
.append("circle");

var circleAttr = circles
.attr("cx", function (d) { return d.x; })
.attr("cy", function (d) { return d.y; })
.attr("r", circleRadii)
.attr("mask", function (d,i) {return "url(#circle_"+i+")"})
.style("fill", function (d) { return d.c; });

var clipedCircle = group.append("circle")
.attr("cx", circleData[0].x)
.attr("cy", circleData[0].y)
.attr("r", circleRadii)
.attr("mask", "url(#circle_0)")
.attr("clip-path", "url(#clip-last-circle)")
.style("fill", circleData[0].c);
body {
    margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>

Upvotes: 3

Related Questions