Inspired by https://www.visualcinnamon.com/2016/05/smooth-color-legend-d3-svg-gradient.html.
Created
August 10, 2017 19:47
-
-
Save darrenjaworski/11eb070bddc04ccd9c03e0331a738bb7 to your computer and use it in GitHub Desktop.
Smooth color svg gradient.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>Document</title> | |
</head> | |
<body> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<script> | |
var width = 50; | |
var height = 600; | |
var color = d3.scaleLinear() | |
.domain([0, .1, 1, 1.01, 3, 3.01, 4.5, 4.51, 6]) | |
.range(['#ffffff', '#CBCBFF', '#004DFF', '#BFFEBF', '#009501', '#FEFEBE', '#E5D42F', '#FEBEBE', '#DC0000']); | |
var svg = d3.select('body') | |
.append('svg') | |
.attr('width', width) | |
.attr('height', height); | |
var defs = svg.append('defs'); | |
var linearGradient = defs.append('linearGradient') | |
.attr('id', 'linear-gradient') | |
.attr('x1', '0%').attr('y1', '100%') | |
.attr('x2', '0%').attr('y2', '0%'); | |
linearGradient.selectAll('stop') | |
.data( color.range() ) | |
.enter() | |
.append('stop') | |
.attr('offset', function(d, i) { | |
return color.domain()[i] / color.domain()[color.domain().length - 1]; | |
}) | |
.attr('stop-color', function(d) { | |
return d; | |
}); | |
svg.append('rect') | |
.attr('width', width) | |
.attr('height', height) | |
.style('fill', 'url(#linear-gradient)'); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment