Skip to content

Instantly share code, notes, and snippets.

@dusadrian
Forked from cjheath/draginthebox.html
Created July 14, 2011 13:57
Show Gist options
  • Save dusadrian/1082501 to your computer and use it in GitHub Desktop.
Save dusadrian/1082501 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"});
myrect.drag(dragMove, dragStart);
function dragStart() {
this.lastX = this.lastY = 0;
var BBox = this.getBBox();
this.absoluteX = BBox.x;
this.absoluteY = BBox.y;
this.width = BBox.width;
this.height = BBox.height;
}
function dragMove(dx, dy) {
var newX = dx - this.lastX;
var newY = dy - this.lastY;
var canvasWidth = container.width();
var canvasHeight = container.height();
if (this.absoluteX + dx + this.width > canvasWidth) {
newX = canvasWidth - this.absoluteX - this.lastX - this.width;
}
if (this.absoluteY + dy + this.height > canvasHeight) {
newY = canvasHeight - this.absoluteY - this.lastY - this.height;
}
if (this.absoluteX + dx < 0) {
newX = - (this.absoluteX + this.lastX);
}
if (this.absoluteY + dy < 0) {
newY = - (this.absoluteY + this.lastY);
}
this.translate(newX, newY);
if (this.absoluteX + dx < 0) {
this.lastX = - this.absoluteX;
}
else {
this.lastX += newX;
}
if (this.absoluteY + dy < 0) {
this.lastY = - this.absoluteY;
}
else {
this.lastY += newY;
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment