Built with blockbuilder.org
Created
May 18, 2017 08:06
-
-
Save Jverma/8a6b64f9dbfc4ecdd3047697e59305a7 to your computer and use it in GitHub Desktop.
Canvas + D3: Plotting 20K points
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
license: mit |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Canvas Scatterplot</title> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<script src="http://d3js.org/d3.v4.js"></script> | |
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script> | |
<script src="https://d3js.org/d3-scale.v1.min.js"></script> | |
</head> | |
<body> | |
<div id="container"></div> | |
<script type="text/javascript"> | |
var data = []; | |
d3.range(20000).forEach(function(el){ | |
data.push({ x: d3.randomNormal(5,3)(), y: d3.randomNormal(5,3)(), r: d3.randomNormal(3,1)() }); | |
}); | |
console.log(data); | |
var width = 1400, | |
height = 750; | |
var canvas = d3.select('#container') | |
.append('canvas') | |
.attr('width', width) | |
.attr('height', height); | |
var context = canvas.node().getContext('2d'); | |
var customBase = document.createElement('custom'); | |
var custom = d3.select(customBase); // replacement of SVG | |
var x = d3.scaleLinear() | |
.domain([2, 8]) | |
.range([0, width]); | |
var y = d3.scaleLinear() | |
.domain([2,8]) | |
.range([height, 0]); | |
databind(data, x, y); | |
var t = d3.timer(function(elapsed){ | |
draw(); | |
if (elapsed > 300) t.stop(); | |
// timer running the draw function repeatedly for 300ms. | |
}); | |
function databind(data, x, y){ | |
var join = custom.selectAll('custon.circle') | |
.data(data); | |
var enterSel = join.enter() | |
.append('custom') | |
.attr('class', 'circle') | |
.attr('x', function(d,i){ | |
return x(d.x); | |
}) | |
.attr('y', function(d,i){ | |
return y(d.y); | |
}) | |
.attr('r', function(d,i){ | |
return Math.abs(d.r); | |
}); | |
} | |
function draw(){ | |
context.clearRect(0, 0, width, height); | |
var elements = custom.selectAll('custom.circle'); | |
elements.each(function(d,i){ | |
var node = d3.select(this); | |
context.fillStyle = 'steelblue'; | |
context.beginPath(); | |
context.arc(node.attr('x'), node.attr('y'), node.attr('r'), 0, 2*Math.PI); | |
context.fill(); | |
}) | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment