Skip to content

Instantly share code, notes, and snippets.

@nbremer
Last active January 30, 2018 13:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save nbremer/6f5b472cabe8f85583989a40eef0303c to your computer and use it in GitHub Desktop.
Save nbremer/6f5b472cabe8f85583989a40eef0303c to your computer and use it in GitHub Desktop.
Animated gradient - Simple rectangle
height: 140
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<!-- D3.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
<style>
body {
text-align: center;
}
</style>
</head>
<body>
<div id="widthMeasure"></div>
<div id="chart"></div>
<script language="javascript" type="text/javascript">
///////////////////////////////////////////////////////////////////////////
//////////////////// Set up and initiate svg containers ///////////////////
///////////////////////////////////////////////////////////////////////////
var margin = {
top: 20,
right: 20,
bottom: 20,
left: 20
};
var width = document.getElementById('widthMeasure').offsetWidth - margin.left - margin.right - 10,
height = 100;
//SVG container
var svg = d3.select("#chart")
.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 + ")");
///////////////////////////////////////////////////////////////////////////
/////////////////////////// Create the gradients //////////////////////////
///////////////////////////////////////////////////////////////////////////
//Container for the gradients
var defs = svg.append("defs");
var linearGradient = defs.append("linearGradient")
.attr("id","animate-gradient")
.attr("x1","0%")
.attr("y1","0%")
.attr("x2","100%")
.attr("y2","0")
.attr("spreadMethod", "reflect");
var colours = ["#FDA860", "#FC8669", "#E36172", "#C64277", "#E36172", "#FC8669" ,"#FDA860"];
linearGradient.selectAll(".stop")
.data(colours)
.enter().append("stop")
.attr("offset", function(d,i) { return i/(colours.length-1); })
.attr("stop-color", function(d) { return d; });
linearGradient.append("animate")
.attr("attributeName","x1")
.attr("values","0%;100%")
.attr("dur","7s")
.attr("repeatCount","indefinite");
linearGradient.append("animate")
.attr("attributeName","x2")
.attr("values","100%;200%")
.attr("dur","7s")
.attr("repeatCount","indefinite");
///////////////////////////////////////////////////////////////////////////
////////////////////////// Create the rectangle ///////////////////////////
///////////////////////////////////////////////////////////////////////////
svg.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", width)
.attr("height", height)
.style("fill", "url(#animate-gradient)");
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment