Skip to content

Instantly share code, notes, and snippets.

@jdpersona
Created March 25, 2018 20:22
Show Gist options
  • Save jdpersona/abf6dc575a2439b3b78aebf08b20893f to your computer and use it in GitHub Desktop.
Save jdpersona/abf6dc575a2439b3b78aebf08b20893f to your computer and use it in GitHub Desktop.
general update patterns - svg
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>general update pattern</title>
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0 px; }
</style>
</head>
<body>
<!-- <svg width='960' height='500'>
<circle cx='161', cy='160', r='150', fill='rgba(255, 0, 0, 0.5)'></circle>
</svg>
-->
<script>
function render(data){
svg = d3.select('body').selectAll('svg').data([null]);
// because svg is a constant variable, so we don't need to define it with const.
svg = svg.merge(svg.enter().append('svg')
.attr('width', 871)
.attr('height', 297));
const rects = svg.selectAll('.p') //class: .x
.data(data);
rects
.merge(rects.enter().append('rect')
.attr('class', 'p')
.attr('y', 100)
.attr('width', 70)
.attr('height', 2000)
.attr('fill', 'green'))
.attr('x', function(d){ return d; });
rects
.exit().remove();
}
render([80, 162]); //Enter
//render([51, 126, 200]); //Enter + Update
//render([3]); //Exit
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment