Skip to content

Instantly share code, notes, and snippets.

@cjheath
Forked from dusadrian/draginthebox.html
Created July 16, 2011 01:23
Show Gist options
  • Save cjheath/1085883 to your computer and use it in GitHub Desktop.
Save cjheath/1085883 to your computer and use it in GitHub Desktop.
Shows how to restrict Raphael's dragging to a specified region, in this case, the canvas
<html>
<head>
<script src="https://github.com/DmitryBaranovskiy/raphael/raw/master/raphael-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
</head>
<body>
<div id="container" style="position:absolute;left:25%;right:25%;top:25%;bottom:25%;background-color:#DDD">
</div>
<script type='text/javascript'>
var container = $('#container');
var paper = Raphael(container[0], '100%', '100%');
var myrect = paper.rect(50, 50, 50, 50);
myrect.attr({fill: "#f00"});
(function(obj) {
var lastX = 0, lastY = 0;
var BBox = obj.getBBox();
var absoluteX = BBox.x;
var absoluteY = BBox.y;
var width = BBox.width;
var height = BBox.height;
var dragStart = function() {
absoluteX = BBox.x;
absoluteY = BBox.y;
width = BBox.width;
height = BBox.height;
};
var dragMove = function(dx, dy) { // dx, dy are relative to where the drag started
var newX = dx - lastX;
var newY = dy - lastY;
var canvasWidth = container.width();
var canvasHeight = container.height();
if (absoluteX + dx + width > canvasWidth) {
newX = canvasWidth - absoluteX - lastX - width;
}
if (absoluteY + dy + height > canvasHeight) {
newY = canvasHeight - absoluteY - lastY - height;
}
if (absoluteX + dx < 0) {
newX = - (absoluteX + lastX);
}
if (absoluteY + dy < 0) {
newY = - (absoluteY + lastY);
}
this.translate(newX, newY);
if (absoluteX + dx < 0) {
lastX = - absoluteX;
}
else {
lastX += newX;
}
if (absoluteY + dy < 0) {
lastY = - absoluteY;
}
else {
lastY += newY;
}
};
obj.drag(dragMove, dragStart);
})(myrect);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment