Skip to content

Instantly share code, notes, and snippets.

@jerryorr
Last active August 29, 2015 14:21
Show Gist options
  • Save jerryorr/c3fe73ea999d4cc3dfc3 to your computer and use it in GitHub Desktop.
Save jerryorr/c3fe73ea999d4cc3dfc3 to your computer and use it in GitHub Desktop.
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
</head>
<body>
<div class="container"></div>
</body>
<script type="text/javascript">
var root = d3.selectAll('body .container').selectAll('.widget')
function draw (data) {
root = root.data([data])
//root enter
var enter = root
.enter()
.append('div')
.classed('widget', true)
// label enter
enter
.append('div')
.classed('label', true)
// update
root.select('.label')
.text(function (d) {
return d.label
})
// Destroying the shape since the element type might change
// root.select('.shape').remove()
// svg enter
enter
.append('svg')
.attr('height', '100%')
.attr('width', '100%')
.append(function (d) {
return document.createElementNS('http://www.w3.org/2000/svg', d.shape)
})
.classed('shape', true)
// svg update
root.select('.shape')
.attr('width', function (d) {
return d.width
})
.attr('height', function (d) {
return d.height
})
.attr('cx', function (d) {
return d.width / 2
})
.attr('cy', function (d) {
return d.height / 2
})
.attr('r', function (d) {
return d.width / 2
})
.attr('stroke', 'red')
.attr('fill', 'red')
}
draw({
shape: 'rect',
label: 'Hello',
width: 100,
height: 200
})
setTimeout(function () {
draw({
shape: 'circle',
label: 'Goodbye',
width: 250,
height: 400
})
}, 1000)
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment