Created
November 27, 2013 10:38
-
-
Save brainwipe/7673707 to your computer and use it in GitHub Desktop.
Using Snap.svg to create a draggable box that snaps to grid.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
@richban change lines 32 and 33 to:
orig.x = e.target.x.baseVal.value; orig.y = e.target.y.baseVal.value;
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
I like your example, however I encounter and error at 2nd function orig.x = e.toElement.x.baseVal.value; I don't understand how are you updating this position. Could please try explain me?