Skip to content

Instantly share code, notes, and snippets.

@clhenrick
Last active May 14, 2017
Embed
What would you like to do?
D3 + Canvas demo
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<div class="container"></div>
<script>
var width = 500;
var height = 420;
var barw = 50;
var barh = 50;
// create a canvas element within our div.container
var canvas = d3.select('.container')
.append('canvas')
.attr('width', width)
.attr('height', height);
// a reference to our canvas' context, a "toolbox"
var context = canvas.node().getContext('2d');
// make some data
//var data = [5, 40, 90, 500];
var data = d3.range(1000).map(d => d);
// create our x scale
var x = d3.scaleLinear()
.range([10, width - 10])
.domain(d3.extent(data));
// create our color scale
var colorScale = d3.scaleSequential(d3.interpolateSpectral)
.domain(d3.extent(data));
// loop over our data and draw on the canvas
data.forEach((d, i) => {
context.fillStyle = colorScale(d);
context.fillRect(x(d), 10, 50, 50);
if (d % 50 === 0) {
context.fillStyle = colorScale(d);
context.fillRect(x(d), 70, barw, barh);
}
if (d % 100 === 0) {
context.fillStyle = colorScale(d);
context.fillRect(x(d), 130, barw, barh);
}
if (d % 150 === 0) {
context.fillStyle = colorScale(d);
context.fillRect(x(d), 190, barw, barh);
}
if (d % 200 === 0) {
context.fillStyle = colorScale(d);
context.fillRect(x(d), 250, barw, barh);
}
if (d % 250 === 0) {
context.fillStyle = colorScale(d);
context.fillRect(x(d), 310, barw, barh);
}
if (d % 300 === 0) {
context.fillStyle = colorScale(d);
context.fillRect(x(d), 370, barw, barh);
}
});
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment