Skip to content

Instantly share code, notes, and snippets.

@clhenrick
Last active February 18, 2020 17:54
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 clhenrick/82239ba866b2d31c6da9ffbb83934a15 to your computer and use it in GitHub Desktop.
Save clhenrick/82239ba866b2d31c6da9ffbb83934a15 to your computer and use it in GitHub Desktop.
D3 Canvas color transition II
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
html, body { margin:0;position:relative; width: 100%; height: 100%; background: #222 }
canvas { position: absolute; display: block; top: calc(50% - 200px); left: calc(50% - 200px);}
</style>
</head>
<body>
<canvas id="canvas" width=400 height=400></canvas>
<script>
// grab our canvas element & it's 2d context
var canvas = d3.select("#canvas");
var context = canvas.node().getContext('2d');
// create a new color using D3's HSL color space
var startColor = d3.hsl('red');
// shift hue by `deg` number of degrees
var rotateHue = function(deg) {
startColor.h += deg;
return startColor;
}
// update the canvas with a colored circle
var setColor = function setColor(val) {
context.clearRect(0, 0, 400, 400);
context.fillStyle = rotateHue(val);
context.arc(200, 200, 200, 0, 2 * Math.PI, true);
context.fill();
context.closePath();
}
// use D3 interval to create the animation, incrementing
// hue value each function call
// if it reaches 360, set it back to 0
var x = 0;
var t = d3.interval(function() {
if (x < 360) {
x += 0.005;
setColor(x);
} else {
x = 0;
}
}, 100);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment