Skip to content

Instantly share code, notes, and snippets.

@jsl6906
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsl6906/89ef40de1d8808d04f42 to your computer and use it in GitHub Desktop.
Save jsl6906/89ef40de1d8808d04f42 to your computer and use it in GitHub Desktop.
colorUnderCurve

An example displaying how to color under a curve using svg clipping paths. Drag left and right on the chart to move the area being highlighted.

<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<style>
body {
cursor: e-resize;
}
.axis text {
font: 10px sans-serif;
}
.axis path, .axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.backArea {
fill: #BEBDBD;
stroke: none;
}
.backLine {
fill: none;
stroke: #9E9C9D;
stroke-width: 2px;
}
.foreArea {
fill: #8888FF;
stroke: none;
clip-path: url(#clipRect);
}
.foreLine {
fill: none;
stroke: #2020FF;
stroke-width: 2px;
clip-path: url(#clipRect);
}
#clipRect {
fill: none;
stroke: red;
}
</style>
<script>
var margin = {top: 10, right: 10, bottom: 30, left: 30},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var lineData = [
{x: 0, y: 1},
{x: 1, y: 2},
{x: 2, y: 4},
{x: 3, y: 6},
{x: 4, y: 3},
{x: 5, y: 1}
];
var x = d3.scale.linear()
.domain([0, 5])
.range([0, width]),
y = d3.scale.linear()
.domain([0, 7])
.range([height, 0]),
xAxis = d3.svg.axis()
.scale(x)
.orient("bottom"),
yAxis = d3.svg.axis()
.scale(y)
.orient("left"),
line = d3.svg.line()
.x(function(d) { return x(d.x); })
.y(function(d) { return y(d.y); })
.interpolate("cardinal"),
area = d3.svg.area()
.x(function(d) { return x(d.x); })
.y0(y(0))
.y1(function(d) { return y(d.y); })
.interpolate("cardinal"),
drag = d3.behavior.drag()
.on("drag", dragBox);
var svg = d3.select("body").call(drag)
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append("path")
.attr("class", "backArea")
.attr("d", area(lineData));
svg.append("path")
.attr("class", "backLine")
.attr("d", line(lineData));
svg.append("path")
.attr("class", "foreArea")
.attr("d", area(lineData));
svg.append("path")
.attr("class", "foreLine")
.attr("d", line(lineData));
svg.append("clipPath")
.attr("id", "clipRect")
.append("rect")
.attr("x", x(1.5))
.attr("width", x(1))
.attr("height", height);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
function dragBox() {
var rect = d3.select("#clipRect rect");
rect.attr("x", +rect.attr("x") + d3.event.dx);
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment