Skip to content

Instantly share code, notes, and snippets.

@aaizemberg
Last active November 20, 2015 21:07
Show Gist options
  • Save aaizemberg/55e41026d50a607c8b6e to your computer and use it in GitHub Desktop.
Save aaizemberg/55e41026d50a607c8b6e to your computer and use it in GitHub Desktop.
Color Interpolate (RGB, HSL & CubeHelix)

Comparando la interpolación de colores con RGB, HSL y CubeHelix

<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
<title>Color Interpolate (RGB, HSL, CubeHelix)</title>
</head>
<body>
<div id="rgb"></div>
<div id="hsl"></div>
<div id="cubehelix"></div>
<script>
// https://github.com/d3/d3-plugins/blob/master/cubehelix/cubehelix.js
(function() {
var radians = Math.PI / 180;
d3.scale.cubehelix = function() {
return d3.scale.linear()
.range([d3.hsl(300, 0.5, 0), d3.hsl(-240, 0.5, 1)])
.interpolate(d3.interpolateCubehelix);
};
d3.interpolateCubehelix = d3_interpolateCubehelix(1);
d3.interpolateCubehelix.gamma = d3_interpolateCubehelix;
function d3_interpolateCubehelix(γ) {
return function(a, b) {
a = d3.hsl(a);
b = d3.hsl(b);
var ah = (a.h + 120) * radians,
bh = (b.h + 120) * radians - ah,
as = a.s,
bs = b.s - as,
al = a.l,
bl = b.l - al;
// if (isNaN(bs)) bs = 0, as = isNaN(as) ? b.s : as;
// if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah;
return function(t) {
var h = ah + bh * t,
l = Math.pow(al + bl * t, γ),
a = (as + bs * t) * l * (1 - l),
cosh = Math.cos(h),
sinh = Math.sin(h);
return "#" +
hex(l + a * (-0.14861 * cosh + 1.78277 * sinh)) +
hex(l + a * (-0.29227 * cosh - 0.90649 * sinh)) +
hex(l + a * (+1.97294 * cosh));
};
};
}
function hex(v) {
var s = (v = v <= 0 ? 0 : v >= 1 ? 255 : v * 255 | 0).toString(16);
return v < 0x10 ? "0" + s : s;
}
})();
var a = "blue";
var b = "red";
var c1 = d3.interpolateRgb(a, b);
var c2 = d3.interpolateHsl(a, b);
// var c3 = d3.interpolateCubehelix("hsl(300,50%,0%)", "hsl(-240,50%,100%)");
// d3.hsl(300, .5, 0) ,d3.hsl(-240, .5, 1)
var c3 = d3.scale.cubehelix();
var width = 200, height = 200, radius = Math.min(width, height) / 2;
var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(50);
var data = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d; });
function draw(id, color) {
var svg = d3.select(id).append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var g = svg.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
//.attr("stroke", "#fff")
.style("fill", function(d,i) {return color(i / data.length);});
}
draw("div#rgb", c1);
draw("div#hsl", c2);
draw("div#cubehelix", c3);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment