Skip to content

Instantly share code, notes, and snippets.

@espinielli
Last active November 8, 2015 12:56
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 espinielli/b717ed2cc0d1a9a789ae to your computer and use it in GitHub Desktop.
Save espinielli/b717ed2cc0d1a9a789ae to your computer and use it in GitHub Desktop.
D3 keybinding with jwerty

Perform keyboard combinations binding using Keith Cirkel's jwerty in D3.js.

In this gist, use arrow keys to translate and ⇧+↑ (Shift + arrow-up) / ⇧+↓ (Shift + arrow-down) to rotate counterclockwise/clockwise.

Inspired by Tom MacWright's gist and Ian Johnson's waves.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font:12px/20px 'Helvetica';
}
svg {
background: #ccc;
}
</style>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jwerty/0.3.2/jwerty.min.js"></script>
<body>
<p>Use arrow keys to translate.<br>
Use ⇧+↑ (Shift + arrow-up) to rotate counterclockwise.<br>
Use ⇧+↓ (Shift + arrow-down) to rotate clockwise.</p>
<p><small>Inspired by Tom MacWright's <a href="http://bl.ocks.org/tmcw/4444952">gist</a> and Keith Cirkel's <a href="http://keithcirkel.co.uk/jwerty/">jwerty</a></small></p>
<script>
var width = 400, height = 300;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var grp = svg.append("g")
.attr("transform", "translate(0,0) rotate(0)");
var point = [width/2, height/2, 0];
var momentum = [0, 0];
var rotation = 0;
var points = [
{ "x": 0, "y": 0},
{ "x": 20, "y": 60},
{ "x": 40, "y": 0},
{ "x": 0, "y": 0} ];
var lineFunction = d3.svg.line()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; })
.interpolate("linear");
var shape = grp.append("path")
.data(points)
.attr("d", lineFunction(points))
.attr("stroke", "blue")
.attr("stroke-width", 2)
.attr("fill", "red");
function move(x, y) {
return function(event) {
event.preventDefault();
momentum = [momentum[0] + x, momentum[1] + y];
};
}
function rotate(a) {
return function(event) {
event.preventDefault();
rotation += a;
};
}
jwerty.key('←', move(-2, 0), grp);
jwerty.key('↑', move(0, -2), grp);
jwerty.key('→', move(2, 0), grp);
jwerty.key('↓', move(0, 2), grp);
jwerty.key('shift+↑', rotate(-2), grp);
jwerty.key('shift+↓', rotate(+2), grp);
d3.timer(function() {
point[0] = Math.min(width-10, Math.max(10, momentum[0] + point[0]));
point[1] = Math.min(height-10, Math.max(10, momentum[1] + point[1]));
point[2] = rotation;
grp
.attr('transform', function() { return 'translate('+point[0]+','+point[1]+')rotate('+point[2]+')'; });
momentum[0] *= 0.9;
momentum[1] *= 0.9;
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment