Skip to content

Instantly share code, notes, and snippets.

@typable
Last active April 28, 2021 15:21
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 typable/d7d0339db454b7dce48879d3a95c33ff to your computer and use it in GitHub Desktop.
Save typable/d7d0339db454b7dce48879d3a95c33ff to your computer and use it in GitHub Desktop.
Canvas Mouse Dragging
// state
state = {
origin: { x: 0, y: 0 },
move: { x: 0, y: 0 },
scale: 1,
delta: 0.5,
dragging: false,
min: 1,
max: 100
};
// transform function
(a, scale, b) => a / scale - b;
// 'mousedown' event
(event) => {
state.dragging = true;
state.move.x = transform(event.layerX, state.scale, state.origin.x);
state.move.y = transform(event.layerY, state.scale, state.origin.y);
};
// 'mouseup' event
(event) => state.dragging = false;
// 'mousemove' event
(event) => {
if(state.dragging) {
state.origin.x = transform(event.layerX, state.scale, state.move.x);
state.origin.y = transform(event.layerY, state.scale, state.move.y);
}
};
// 'wheel' event
(event) => {
let delta = 0;
if(event.deltaY < 0) {
if(state.scale < state.max) {
delta = state.delta;
}
}
else {
if(state.scale > state.min) {
delta = -state.delta;
}
}
if(state.scale + delta < 1) {
state.scale = 1;
}
else {
state.scale += delta;
}
let ax = transform(event.layerX, state.scale - delta, state.origin.x);
let bx = transform(event.layerX, state.scale, state.origin.x);
state.origin.x -= ax - bx;
let ay = transform(event.layerY, state.scale - delta, state.origin.y);
let by = transform(event.layerY, state.scale, state.origin.y);
state.origin.y -= ay - by;
};
// get transformed location
(x, y) => {
return {
x: transform(x, state.scale, state.origin.x),
y: transform(y, state.scale, state.origin.y)
};
};
// draw transformed circle
// x = (o.x + x) * s
// y = (o.y + y) * s
({ x, y }, r) => {
g.beginPath();
g.arc((state.origin.x + x) * state.scale, (state.origin.y + y) * state.scale, r * state.scale, 0, 2 * Math.PI, false);
g.stroke();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment