Skip to content

Instantly share code, notes, and snippets.

@tmpvar
Created December 18, 2013 20:21
Show Gist options
  • Save tmpvar/8029270 to your computer and use it in GitHub Desktop.
Save tmpvar/8029270 to your computer and use it in GitHub Desktop.
testing out an approach to apply modes to a mousemove stream
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
function source(fn) {
canvas.addEventListener('mousemove', fn);
}
function simplify(fn) {
return function(val) {
fn({
x: val.x,
y: val.y
});
};
}
function snap(gridSize) {
return function(e, fn) {
fn({
x : Math.round(e.x / gridSize)*gridSize,
y : Math.round(e.y / gridSize)*gridSize
});
};
}
function mode(fn) {
var ret = function(val, next) {
ret.mode(val, fn);
};
// set the initial mode
ret.mode = fn;
return ret;
}
function render(coords) {
canvas.width = 0;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.strokeStyle = "yellow";
ctx.beginPath();
ctx.translate(coords.x, coords.y);
ctx.arc(0, 0, 20, Math.PI*2, false);
ctx.closePath();
ctx.stroke();
ctx.restore();
}
var modeManager = mode(render);
var snappingMode = snap(100);
var normalMode = render;
// Press S to toggle snapping
document.addEventListener('keydown', function(ev) {
if (ev.keyCode === 83) { // s
if (modeManager.mode === normalMode) {
modeManager.mode = snappingMode;
console.log('snapping on');
} else {
modeManager.mode = normalMode;
console.log('snapping off');
}
}
});
source(simplify(modeManager));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment