Skip to content

Instantly share code, notes, and snippets.

@plmrry
Last active July 27, 2016 02:48
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 plmrry/a23c79db3a30af301386123279f9709b to your computer and use it in GitHub Desktop.
Save plmrry/a23c79db3a30af301386123279f9709b to your computer and use it in GitHub Desktop.
Force Transition
license: gpl-3.0
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.10.3/babel.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<script>
d3.text('script.js', function(err, source) {
var options = { presets: ['es2015'] };
var compiled = Babel.transform(source, options).code;
(new Function(compiled))();
})
</script>
</body>
var svg = d3.select("body").append("svg")
.attr("width", 360)
.attr("height", 200);
var svg = d3.select("svg"),
margin = {top: 40, right: 40, bottom: 40, left: 40},
width = svg.attr("width") - margin.left - margin.right,
height = svg.attr("height") - margin.top - margin.bottom;
var formatValue = d3.format(",d");
var x = d3.scaleLinear()
.rangeRound([0, width]);
var g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
const data = d3.range(100).map(d => ({ value: Math.random() }))
x.domain(d3.extent(data, function(d) { return d.value; }));
const x1 = d3.forceX(function(d) { return x(0.75); }).strength(0.1);
const x2 = d3.forceX(function(d) { return x(0.25); }).strength(0);
var simulation = d3.forceSimulation(data)
.force("x", x1)
.force('x2', x2)
.force("y", d3.forceY(height / 2))
.force("collide", d3.forceCollide(4))
.on('tick', ticked)
d3.select('body').append('button').text('switch').on('click', change);
let foo = true;
let strength = 0;
function change() {
foo = !foo;
const end = foo ? 0.3 : 0;
// d3.transition()
// .duration(2000)
// .tween('x', () => {
// const i = d3.interpolate(strength, end);
// return (t) => {
// strength = i(t);
// x2.strength(strength);
// }
// })
if (foo) {
x1.strength(0.3);
x2.strength(0);
} else {
x1.strength(0);
x2.strength(0.3);
}
simulation.alpha(0.2).restart();
}
g.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x).ticks(5));
var cell = g.append("g")
.attr("class", "cells")
.selectAll("g").data(data).enter().append("g");
cell.append("circle")
.attr("r", 3);
function ticked() {
d3.selectAll('circle')
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment