Skip to content

Instantly share code, notes, and snippets.

@seemantk
Last active September 4, 2016 15:54
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 seemantk/5c24dc52841eaa5df7bd77bc127bf9c9 to your computer and use it in GitHub Desktop.
Save seemantk/5c24dc52841eaa5df7bd77bc127bf9c9 to your computer and use it in GitHub Desktop.
Partially filling rectangles with linear gradients
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta author="Seemant Kulleen">
<meta description="Using SVG:LinearGradients to partially fill rectangles.">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
rect {
stroke: black;
}
.bar {
stop-opacity: 1;
stop-color: red;
}
.empty {
stop-color: blue;
}
.clear {
stop-opacity: 0;
}
</style>
</head>
<body>
<svg width="960" height="500">
<defs>
<linearGradient id="gradient1" x1="0" x2="1" y1="0" y2="0">
<stop offset="0%" stop-color="red"></stop>
<stop offset="100%" stop-color="blue"></stop>
</linearGradient>
<linearGradient id="gradient-2stops" x1="0" x2="1" y1="0" y2="0">
<stop offset="0%" stop-color="red"></stop>
<stop offset="57%" stop-color="red"></stop>
<stop offset="100%" stop-color="blue"></stop>
</linearGradient>
<linearGradient id="gradient-3stops" x1="0" x2="1" y1="0" y2="0">
<stop offset="0%" stop-color="red"></stop>
<stop offset="57%" stop-color="red"></stop>
<stop offset="57%" stop-color="blue"></stop>
</linearGradient>
<linearGradient id="gradient-css" x1="0" x2="1" y1="0" y2="0">
<stop offset="0%" class="bar"></stop>
<stop offset="57%" class="bar"></stop>
<stop offset="57%" class="empty"></stop>
</linearGradient>
<linearGradient id="gradient-opacity" x1="0" x2="1" y1="0" y2="0">
<stop offset="0%" class="bar"></stop>
<stop offset="57%" class="bar"></stop>
<stop offset="57%" class="clear"></stop>
</linearGradient>
</defs>
<g class="axis"></g>
<rect x="50" y="50" width="400" height="50" style="fill: url(#gradient1); stroke: black;"></rect>
<g class="axis"></g>
<rect x="50" y="150" width="400" height="50" style="fill: url(#gradient-2stops); stroke: black;"></rect>
<g class="axis"></g>
<rect x="50" y="250" width="400" height="50" style="fill: url(#gradient-3stops); stroke: black;"></rect>
<g class="axis"></g>
<rect x="50" y="350" width="400" height="50" style="fill: url(#gradient-css); stroke: black;"></rect>
<g class="axis"></g>
<rect x="50" y="450" width="400" height="50" style="fill: url(#gradient-opacity);"></rect>
</svg>
<script>
var scale = d3.scaleLinear().domain([0,100]).range([0,400])
, axis = d3.axisTop().scale(scale)
;
d3.selectAll(".axis")
.attr("transform", function(d, i) { console.log(i * 100 + 50); return "translate(50," + ((i * 100) + 50) + ")"; })
.call(axis)
;
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment