Built with blockbuilder.org
Last active
April 2, 2020 22:02
-
-
Save EE2dev/e653b5c781b642c164bd4710031243ca to your computer and use it in GitHub Desktop.
fresh block
This file contains hidden or 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 hidden or 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> | |
<h1><code>d3.js</code>, Force Layout primer</h1> | |
<h2>For study purposes only</h2> | |
<ul> | |
<li>Cleaned up an example from : | |
https://bl.ocks.org/mbostock/1095795/8f34afdd6d321b71ca6b3a5904e486f3173f1111</li> | |
<li>Cleaned up example uses d3 version 5.</li> | |
<li>Original example license : https://opensource.org/licenses/GPL-3.0</li> | |
<li>Original example uses d3 version 4.</li> | |
</ul> | |
<p> | |
fork and updated from from https://bl.ocks.org/jerng/b47cf70fc0fd20ccf56cdb42e172e877 | |
</p> | |
<script src="https://d3js.org/d3.v5.min.js"></script> | |
<script> | |
'use strict' | |
let width = 500, | |
height = 500, | |
color = d3.scaleOrdinal(d3.schemeCategory10), | |
svg = d3.select ( 'body' ) | |
.insert ( 'svg' ) | |
.attr ( 'width', width ) | |
.attr ( 'height', height ) | |
.attr ( 'style', 'background-color:#eeeeee' ) | |
let a = { id: 'a' }, | |
b = { id: 'b' }, | |
c = { id: 'c' }, | |
dataArray = [ a, b, c ] | |
let g = svg.append ( 'g' ) | |
.attr ( 'transform', | |
'translate( ' + width / 2 + ',' + height / 2 + ' )' ), | |
gg = g.append ( 'g' ) | |
.attr ( 'stroke', '#fff' ) | |
.attr ( 'stroke-width', 1.5) | |
.selectAll () // empty selection | |
let restart = function restart () { | |
gg = gg | |
.data ( dataArray, d => d.id ) | |
.join ( | |
enterer => enterer | |
.append ( 'circle' ) | |
.attr("fill", d => color(d.id) ) | |
.attr("r", 8) | |
) | |
// add these two lines here | |
simulation.nodes( dataArray); | |
simulation.alpha(1).restart(); | |
}, | |
tickHandler = function () { | |
gg .attr( 'cx', d => d.x ) | |
.attr( 'cy', d => d.y ) | |
} | |
let simulation = d3.forceSimulation ( dataArray ) | |
.force ( 'charge', d3.forceManyBody ().strength ( -1000 ) ) | |
.force ( 'x', d3.forceX () ) | |
.force ( 'y', d3.forceY () ) | |
.alphaTarget ( 1 ) | |
.on ( 'tick', tickHandler ) | |
restart() | |
setTimeout ( () => { | |
dataArray.pop() | |
restart() | |
}, 1000 ) | |
setTimeout ( () => { | |
dataArray.push(c) | |
restart() | |
}, 2000 ) | |
setTimeout ( () => { | |
console.error ( `pushing in another value breaks FIXME`, dataArray ) | |
dataArray.push( { id: 'd' } ) | |
restart() | |
}, 3000 ) | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment