Skip to content

Instantly share code, notes, and snippets.

@brainwipe
Created November 27, 2013 10:38
Show Gist options
  • Save brainwipe/7673707 to your computer and use it in GitHub Desktop.
Save brainwipe/7673707 to your computer and use it in GitHub Desktop.
Using Snap.svg to create a draggable box that snaps to grid.
<!DOCTYPE html>
<html>
<head>
<script src="//cdn.jsdelivr.net/snap.svg/0.1.0/snap.svg-min.js"></script>
<script>
var s = Snap("#svg");
var gridSize = 50;
var orig = {
x: 0,
y: 0
};
var block = s.rect(100, 100, 100, 100, 20, 20);
block.attr({
fill: "rgb(236, 240, 241)",
stroke: "#1f2c39",
strokeWidth: 3
});
block.drag(
function (dx, dy, x, y, e) {
var xSnap = Snap.snapTo(gridSize, orig.x + dx, 100000000);
var ySnap = Snap.snapTo(gridSize, orig.y + dy, 100000000);
this.attr({
x: xSnap,
y: ySnap
});
},
function (x, y, e) {
orig.x = e.toElement.x.baseVal.value;
orig.y = e.toElement.y.baseVal.value;
});
</script>
</head>
<body>
<svg id="svg" version="1.1" xmlns="http://www.w3.org/2000/svg"></svg>
</body>
</html>
@ajpaul
Copy link

ajpaul commented May 11, 2016

@richban change lines 32 and 33 to:

orig.x = e.target.x.baseVal.value; orig.y = e.target.y.baseVal.value;

@ajpaul
Copy link

ajpaul commented May 18, 2016

Check this out for more help: https://github.com/ajpaul/SnapSVGgrid

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment