Created
March 10, 2014 05:28
-
-
Save wonga00/9459945 to your computer and use it in GitHub Desktop.
Highlight Selection
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> | |
<meta charset="utf-8"> | |
<body> | |
<style> | |
circle { | |
fill: #ddd; | |
} | |
rect { | |
fill: none; | |
stroke: #FF9797; | |
stroke-width: 1.0; | |
} | |
p { | |
font-size: 12px; | |
margin: 0px; | |
padding: 0px; | |
} | |
</style> | |
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> | |
<script> | |
var NUM_ELEMENTS = 16, | |
data = [], | |
circleSpacing = 30, | |
leftMargin = 20; | |
for (var i = 0; i < NUM_ELEMENTS; i++) { | |
data.push(i); | |
} | |
var svg = d3.select('body').append('svg') | |
.attr('width', 960) | |
.attr('height', 50); | |
var label = d3.select('body').append('p'); | |
svg.selectAll('circle') | |
.data(data) | |
.enter().append('circle') | |
.attr('cx', function(d, i) { | |
return (d * circleSpacing) + leftMargin; | |
}) | |
.attr('cy', 20) | |
.attr('r', 2); | |
function updateSelection(selection) { | |
// draw rect around each selected circle | |
var rectWidth = 20; | |
var rectHeight = 30; | |
var rects = svg.selectAll('rect') | |
.data(selection); | |
// start off screen for nice transition | |
rects.enter().append('rect') | |
.attr('x', -20) | |
.attr('y', 20 - (rectHeight / 2.0)) | |
.attr('height', rectHeight) | |
.attr('width', rectWidth); | |
rects.transition().duration(600).attr('x', function(d, i) { | |
return (d * circleSpacing) + leftMargin - (rectWidth / 2.0); | |
}) | |
.attr('y', 20 - (rectHeight / 2.0)) | |
.attr('height', rectHeight) | |
.attr('width', rectWidth); | |
rects.exit().transition() | |
.attr('x', -20) | |
.remove(); | |
label.text('Selection: ' + selection.join(', ')); | |
} | |
function randomSelect() { | |
var numSelected = Math.round(Math.random() * 4), | |
selection = shuffle(data.slice(0)).slice(0, numSelected); | |
updateSelection(selection); | |
} | |
// Shuffles the input array. | |
function shuffle(array) { | |
var m = array.length, t, i; | |
while (m) { | |
i = Math.floor(Math.random() * m--); | |
t = array[m], array[m] = array[i], array[i] = t; | |
} | |
return array; | |
} | |
setInterval(randomSelect, 1000); | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment