Skip to content

Instantly share code, notes, and snippets.

@armollica
Last active November 25, 2015 03:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save armollica/c3d2b5468b56abb39d41 to your computer and use it in GitHub Desktop.
Save armollica/c3d2b5468b56abb39d41 to your computer and use it in GitHub Desktop.
HSL Grid

Mouse up and down to change the hue. Left and right to change the saturation and lightness.

<html>
<head>
<title>HSL Grid</title>
</head>
<body>
<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
var width = 500,
height = 500;
var scale = {
x: d3.scale.ordinal().rangeRoundBands([0, width]),
y: d3.scale.ordinal().rangeRoundBands([height, 0]),
h: d3.scale.linear().range([0, 50]),
s: d3.scale.sqrt().range([0, 1]),
l: d3.scale.sqrt().range([0, 1]),
mouse: {
x: d3.scale.linear()
.domain([0, width])
.range([0, 1]),
y: d3.scale.linear()
.domain([height, 0])
.range([50, 360])
}
};
var canvas = d3.select("body").append("canvas")
.attr("width", width)
.attr("height", height);
var context = canvas.node().getContext("2d");
var cells = { x: 20, y: 20 };
cells.data = d3.range(cells.x * cells.y)
.map(function(i) {
var x = i % cells.x,
y = Math.floor(i / cells.x);
return { x, y };
});
scale.x.domain(cells.data.map(function(d) { return d.x; }));
scale.y.domain(cells.data.map(function(d) { return d.y; }));
scale.h.domain([0, cells.x * cells.y]);
scale.s.domain([0, cells.x]);
scale.l.domain([0, cells.y]);
draw(cells);
canvas.on("mousemove", function() {
var mouse = d3.mouse(this);
draw(cells, {
x: mouse[0],
y: mouse[1]
});
});
function draw(cells, mouse) {
if (mouse === undefined) mouse = {x: 0, y: 0};
scale.h.range([
scale.mouse.y(mouse.y) - 50,
scale.mouse.y(mouse.y)
]);
scale.s.range([scale.mouse.x(mouse.x), 1]);
scale.l.range([scale.mouse.x(mouse.x), 1]);
cells.data.forEach(function(cell) {
var x = scale.x(cell.x),
y = scale.y(cell.y),
dx = scale.x.rangeBand(),
dy = scale.y.rangeBand(),
h = scale.h(cell.x * cell.y),
s = scale.s(cell.x),
l = scale.l(cell.y),
hsl = d3.hsl(h, s, l);
context.fillStyle = hsl.rgb().toString();
context.fillRect(x, y, dx, dy);
});
}
d3.select(self.frameElement)
.style("width", width + "px")
.style("height", height + "px");
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment