block by nbremer e944485869ac8fd57413a158e9d8aae0

Radial gradient - Simple example - Sun

Full Screen

A simple example of creating a radial SVG gradient used in my blog on Data-based and unique gradients for visualizations with d3.js

Other examples from this Astronomy-themed blog can be found here

Built with blockbuilder.org

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>

	</head>	
	<body>

		<div id="chart" style="text-align: center;"></div>

		<script language="javascript" type="text/javascript">

			///////////////////////////////////////////////////////////////////////////
			//////////////////// Set up and initiate svg containers ///////////////////
			///////////////////////////////////////////////////////////////////////////	

			var margin = {
				top: 0,
				right: 0,
				bottom: 0,
				left: 0
			};
			var width = 300,
				height = 300;
						
			//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 + width/2) + "," + (margin.top + height/2) + ")");

			///////////////////////////////////////////////////////////////////////////
			///////////////////////////// Create gradient /////////////////////////////
			///////////////////////////////////////////////////////////////////////////	

			var defs = svg.append("defs");

			//Create a radial Sun-like gradient
			defs.append("radialGradient")
				.attr("id", "sun-gradient")
				.attr("cx", "50%")	//not really needed, since 50% is the default
				.attr("cy", "50%")	//not really needed, since 50% is the default
				.attr("r", "50%")	//not really needed, since 50% is the default
				.selectAll("stop")
				.data([
						{offset: "0%", color: "#FFF76B"},
						{offset: "50%", color: "#FFF845"},
						{offset: "90%", color: "#FFDA4E"},
						{offset: "100%", color: "#FB8933"}
					])
				.enter().append("stop")
				.attr("offset", function(d) { return d.offset; })
				.attr("stop-color", function(d) { return d.color; });
				
			///////////////////////////////////////////////////////////////////////////
			///////////////////////////// Place the Sun ///////////////////////////////
			///////////////////////////////////////////////////////////////////////////	

			svg.append("circle")
				.attr("r", 100)
				.style("fill", "url(#sun-gradient)");

		</script>

	</body>
</html>