Skip to content

Instantly share code, notes, and snippets.

@romsson
Created April 22, 2018 13:17
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 romsson/96dd417de7d84c36c7dd16f8ebc49c29 to your computer and use it in GitHub Desktop.
Save romsson/96dd417de7d84c36c7dd16f8ebc49c29 to your computer and use it in GitHub Desktop.
D3 bar chart SVG vs Canvas
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
rect {
fill: none;
stroke: black;
stroke-width: 1;
}
</style>
</head>
<body>
<script>
var svg = d3.select("body").append("svg")
.attr("width", 960)
.attr("height", 200);
var data = [22, 32, 21, 23, 10, 22, 11, 19, 30, 50, 19, 30, 50, 19, 30, 87];
var y = d3.scaleLinear()
.domain([0, d3.max(data)])
.range([0, 100]);
svg.selectAll("rect").data(data)
.enter()
.append("rect")
.attr("width", 40)
.attr("height", function(d) { return d; })
.attr("x", function(d, i) { return i * 50; })
.attr("y", function(d) { return 200 - d; })
var canvas = d3.select("body").append("canvas")
.attr("width", 960)
.attr("height", 300);
var context = canvas.node().getContext("2d");
data.forEach(function(d, i) {
context.beginPath();
context.rect(i * 50, 100 - y(d), 40, y(d));
context.strokeStyle ="black";
context.stroke();
context.closePath();
});
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment