block by nbremer 6f5b472cabe8f85583989a40eef0303c

Animated gradient - Simple rectangle

Full Screen

This is a simple example showing how you can easily animate a gradient to mimic a flow

Other examples of animated gradients can be found here

Note that Safari cannot handle the spreadMethod reflect, thus the gradient looks a bit weird in Safari. Try looking at this in Chrome or Firefox

index.html

<!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>