Skip to content

Instantly share code, notes, and snippets.

@yonester
Last active August 16, 2017 18:02
Show Gist options
  • Save yonester/acf5f6a52c370a3d1fa5cc08ba955db9 to your computer and use it in GitHub Desktop.
Save yonester/acf5f6a52c370a3d1fa5cc08ba955db9 to your computer and use it in GitHub Desktop.
Canvas vs. SVG Test

A comparison between rendering circles in SVG and canvas. The functions are purposely written separately but similarly to show some key differences. Notably, SVG's structure allows us to take advantage of D3's wonderful data binding capabilities, which makes diffing new data against present data expressive and easy. Canvas will perform better when animating many nodes (not shown here) and makes styling more succinct, but try zooming in a couple of steps (Cmd-plus in OSX, Ctrl-plus in Windows) to see the difference between rendering pixels and vectors.

<!DOCTYPE html>
<meta charset="utf-8">
<canvas width="960" height="110"></canvas>
<svg width="960" height="110"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
const radii = d3.range(1, 50, 3);
(function drawCanvas() {
const canvas = document.querySelector('canvas');
const context = canvas.getContext('2d');
let x = 0;
context.fillStyle = 'white';
context.lineWidth = 2;
radii.forEach(d => {
context.beginPath();
context.arc(x += d*2, canvas.height/2, d, 0, 2*Math.PI);
context.stroke();
});
})();
(function drawSVG() {
const svg = d3.select('svg');
const height = +svg.attr('height');
let x = 0;
svg.selectAll('circle')
.data(radii)
.enter()
.append('circle')
.attr('cx', d => x += d*2)
.attr('cy', height/2)
.attr('r', d => d)
.style('fill', 'none')
.style('stroke', 'black')
.style('stroke-width', 2);
})();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment