Skip to content

Instantly share code, notes, and snippets.

Created May 14, 2017 02:52
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save anonymous/5e72ebe2a26df7cdaef36c4a4afa70f3 to your computer and use it in GitHub Desktop.
D3 + Canvas demo
license: mit

D3 + Canvas demo

No data binding, no selection, just drawing using d3 + canvas.

Built with blockbuilder.org

<!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 = 450;
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 = d3.range(1000).map(d => d);
// var data = [5, 40, 90, 500];
// 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), 150, 50, 50);
});
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment