Skip to content

Instantly share code, notes, and snippets.

@tmcw
Created October 24, 2013 13:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmcw/7137263 to your computer and use it in GitHub Desktop.
Save tmcw/7137263 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vector Playground</title>
<meta http-equiv='content-type' content='text/html; charset=utf-8' />
<meta name='viewport' content='initial-scale=1.0 maximum-scale=1.0'>
<style>
g.source-0 path {
stroke:red;
}
g.source-0 circle {
fill:red;
}
g.source-1 path {
stroke:blue;
}
g.source-1 circle {
fill:blue;
}
.result {
stroke:green;
}
path {
stroke-width:5;
}
</style>
</head>
<body>
<div>
<select id='op'>
<option value='add'>add</option>
<option value='subtract'>subtract</option>
</select>
</div>
<script src='http://d3js.org/d3.v3.min.js'></script>
<script src='playground.js'></script>
</body>
</html>
var width = 300,
height = 300,
margin = 10;
var svg = d3.select('body')
.append('svg')
.attr('width', width)
.attr('height', height);
var x = d3.scale.linear()
.range([margin, width - margin])
.domain([-1, 1])
.clamp(true);
var y = d3.scale.linear()
.range([margin, height - margin])
.domain([-1, 1])
.clamp(true);
var sources = [
[[0, 0], [0, 0.1]],
[[0, 0], [0.4, 0]]
];
var line = d3.svg.line()
.x(function(d) {
return x(d[0]);
})
.y(function(d) {
return y(d[1]);
});
var resultpath = svg.append('path')
.attr('class', 'result');
var sourceg = svg.selectAll('g.source')
.data(sources);
var sourcegEnter = sourceg.enter()
.append('g')
.attr('class', function(d, i) {
return 'source source-' + i;
});
var sourcepath = sourcegEnter.append('path');
var dragbehavior = d3.behavior.drag()
.on('drag', function() {
this.__data__[0] = x.invert(d3.event.x);
this.__data__[1] = y.invert(d3.event.y);
movesources();
});
var sourcehandles = sourcegEnter
.selectAll('circle')
.data(function(d) { return [d[1]]; })
.enter()
.append('circle')
.attr('r', 8)
.each(function(d, i) {
d3.select(this).call(dragbehavior);
});
var operations = {
add: add,
subtract: subtract
};
d3.select('#op').on('change', movesources);
movesources();
function movesources() {
var resultdata = operations[getoperation()](sources[0][1], sources[1][1]);
sourcepath.attr('d', line);
resultpath.datum([[0, 0], resultdata]).attr('d', line);
sourcehandles.attr('transform', function(d) {
return 'translate(' + [x(d[0]), y(d[1])] + ')';
});
}
function add(a, b) {
return [
a[0] + b[0],
a[1] + b[1]
];
}
function subtract(a, b) {
return [
a[0] - b[0],
a[1] - b[1]
];
}
function getoperation() {
return d3.select('#op').node().value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment