Skip to content

Instantly share code, notes, and snippets.

@jrbalsano
Last active May 23, 2016 00:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrbalsano/005b19dd896957fcf72a to your computer and use it in GitHub Desktop.
Save jrbalsano/005b19dd896957fcf72a to your computer and use it in GitHub Desktop.
D3 Scatterplot Rendering - 3
<!doctype html>
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var height = 500;
var width = 960;
var timer, startTime;
var startTime;
var BATCH_SIZE = 100;
function showTimeSince(startTime) {
var currentTime = new Date().getTime();
var runtime = currentTime - startTime;
document.getElementById('timeRendering').innerHTML = runtime + 'ms';
}
function startTimer() {
stopTimer();
startTime = new Date().getTime();
timer = setInterval(function() {
showTimeSince(startTime);
}, 10);
showTimeSince(startTime);
}
function stopTimer() {
if (timer) {
clearInterval(timer);
}
showTimeSince(startTime);
}
function drawCircles(svg, data, batchSize) {
startTimer();
var circles = svg.selectAll('circle').data(data);
function drawBatch(batchNumber) {
return function() {
console.log(startIndex);
var startIndex = batchNumber * batchSize;
var stopIndex = Math.min(data.length, startIndex + batchSize);
var updateSelection = d3.selectAll(circles[0].slice(startIndex, stopIndex));
var enterSelection = d3.selectAll(circles.enter()[0].slice(startIndex, stopIndex));
var exitSelection = d3.selectAll(circles.exit()[0].slice(startIndex, stopIndex));
enterSelection.each(function(d, i) {
var newElement = svg.append('circle')[0][0];
enterSelection[0][i] = newElement;
updateSelection[0][i] = newElement;
newElement.__data__ = this.__data__;
}).attr('r', 3);
exitSelection.remove();
updateSelection
.attr('cx', function(d) { return d.x })
.attr('cy', function(d) { return d.y });
if (stopIndex >= data.length) {
stopTimer();
} else {
setTimeout(drawBatch(batchNumber + 1), 0);
}
};
}
setTimeout(drawBatch(0), 0);
}
function renderChart() {
var numPoints = parseInt(document.getElementsByName('numPoints')[0].value, 10);
if (isNaN(numPoints)) {
return;
}
startTimer();
var data = [];
for (var i = 0; i < numPoints; i++) {
data.push({
x: Math.random() * width,
y: Math.random() * height
});
}
var svg = d3.selectAll('svg').data([0]);
svg.enter().append('svg')
.attr("height", height)
.attr("width", width);
drawCircles(svg, data, BATCH_SIZE);
}
</script>
</head>
<body>
<form action="">
<input name="numPoints" type="text" value="10000">
<button type="button" id="render" onClick="renderChart()">Render</button>
</form>
Time Rendering: <span id="timeRendering"></span>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment