# drag constraints in raphael.js and zoom

I've had no problem getting a basic zoom/pan effect with Raphael.js 2.0 using PAN :

set = ( // set of elements, contained in a rectangle) var start = function () { set.oBB = set.getBBox(); }, move = function (dx, dy) { var bb = set.getBBox(); set.translate(set.oBB.x - bb.x + dx, set.oBB.y - bb.y + dy); }, up = function() { // do stuff }; set.drag(move, start, up);

and ZOOM :

//before paper.setViewBox(0,0, 500,500, false); //after paper.setViewBox(0,0, 200, 200, false);

BUT I'm having two big problems with this. This is for a raphael-created svg object and not for an image...

- First, panning AFTER the zoom is not 'smooth' : I drag a little and the rectangle moves a lot. The movement gets worse the farther I go along. Can I scale the drag somehow when I have zoomed?
- Second, how do I arrange so that the panning the zoomed rectangle doesn't let me move it out of the viewport? In jquery I could do this with a constraint, and I've tried playing with the set.translate function above to include constraints but I'm getting nowhere...

Any advice would be appreciated, or else a library which already exists for doing this in Raphael.js? I looked at raphael-spz which doesn't seem to address either of my problems above.

What I'd like is basically this http://dannyvankooten.com/demo/draggable-image-map-with-zoom/ but for Raphael. He's using jquery ui draggable... which I can't seem to get to work in Raphael.

Thanks!

### Answers

Because you have scaled the viewbox you might need to scale the drag values as well, fro calculating bounds you can just compare against the viewport, something like,

move = function (dx, dy) { var bb = set.getBBox(), //Move relative to viewport scale x = dx/scale, y = dy/scale, //Lower bounds xf = Math.max(0, set.oBB.x - bb.x + x), yf = Math.max(0, set.oBB.y - bb.y + y); //upper bounds xf = Math.min(viewBoxWidth, xf + bb.width) - bb.width; yf = Math.min(viewBoxHeight, yf + bb.height) - bb.height; set.translate(xf, yf); }

scale being the factor that your viewbox is different relative to your paper. ie(200/500)