Skip to content

Instantly share code, notes, and snippets.

@pnavarrc
Last active March 2, 2018 11:30
Show Gist options
  • Save pnavarrc/20950640812489f13246 to your computer and use it in GitHub Desktop.
Save pnavarrc/20950640812489f13246 to your computer and use it in GitHub Desktop.
SVG Linear Gradient with D3

SVG Linear Gradient with D3

This example demonstrates how to use gradients in SVG, defining the stop colors completely via CSS. The advantage of this approach is that we can use gradients in shapes without having to hardcode the stop-color attributes when defining the gradients in the SVG element.

References

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>SVG Linear Gradient with D3</title>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<style>
.stop-left {
stop-color: #3f51b5; /* Indigo */
}
.stop-right {
stop-color: #009688; /* Teal */
}
.filled {
fill: url(#mainGradient);
}
.outlined {
fill: none;
stroke: url(#mainGradient);
stroke-width: 4;
}
</style>
</head>
<body>
<div id="svg-container"></div>
<script>
// Create the SVG element and set its dimensions.
var width = 800,
height = 200,
padding = 15;
var div = d3.select('#svg-container'),
svg = div.append('svg');
svg.attr('width', width).attr('height', height);
// Create the svg:defs element and the main gradient definition.
var svgDefs = svg.append('defs');
var mainGradient = svgDefs.append('linearGradient')
.attr('id', 'mainGradient');
// Create the stops of the main gradient. Each stop will be assigned
// a class to style the stop using CSS.
mainGradient.append('stop')
.attr('class', 'stop-left')
.attr('offset', '0');
mainGradient.append('stop')
.attr('class', 'stop-right')
.attr('offset', '1');
// Use the gradient to set the shape fill, via CSS.
svg.append('rect')
.classed('filled', true)
.attr('x', padding)
.attr('y', padding)
.attr('width', (width / 2) - 1.5 * padding)
.attr('height', height - 2 * padding);
// Use the gradient to set the shape stroke, via CSS.
svg.append('rect')
.classed('outlined', true)
.attr('x', width / 2 + padding / 2)
.attr('y', padding)
.attr('width', (width / 2) - 1.5 * padding)
.attr('height', height - 2 * padding);
</script>
</body>
</html>
@Edorka
Copy link

Edorka commented Dec 16, 2015

Great Example, very useful 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment