RaphaelJS : Stop drag when image out of frame

时间:2015-09-14 15:49:52

标签: javascript svg raphael

i have a RaphaelJS paper which has a set that contains an image and other elements. The Image is larger than the paper, and the user can drag it around. However i want the drag to stop so that the image border is never visible, meaning that the user will not the the white margins. I have tried several ways but i keep getting weird results and i cant wrap my head around it. I can get the top left corner of the image and the remaining corners of the image with calculation. Thank you for your time.

UPDATE : i have added a JSFiddle example

In the example i have added a condition that's supposed to keep the top left cornet outside the canvas, but as you can see there are a lot of glitches and bugs with this.

here is an image illustrating the desired result

Code :

Raphael.st.draggable = function(index) {
    var me = this,
            lx = 0,
            ly = 0,
            ox = 0,
            oy = 0,
            moveFnc = function(dx, dy) {
                x = set.getBBox().x;
                y = set.getBBox().y;
                console.log(x+":"+y);
                lx = dx + ox;
                ly = dy + oy;
                if(x+dx < 0 && y+dy < 0)//REMOVE THIS CONDITION FOR FREE DRAG
                    me.transform(',,320,240,'+'t' + lx + ',' + ly);

        },
        startFnc = function() {},
        endFnc = function() {
            ox = lx;
            oy = ly;
        };
    this.drag(moveFnc, startFnc, endFnc);
    };
width = 640;
height = 480;
paper = Raphael(cur_id, width, height),

image = paper.image('http://edwardtufte.com.s3.amazonaws.com/Thinking%20Eye/ParisMap.gif', 0, 0,950,805)
set = paper.set();
set.push(image);
paper.canvas.style.backgroundColor = "#FF0000"
set.draggable();

1 个答案:

答案 0 :(得分:0)

如果我了解您正在寻找的内容,看起来您只是错过了moveFnc拖动事件中的限制部分。

代替你的lx和ly分配这样的东西应该限制图像只能滚动到边缘:

           if (dx + ox <= 0){
                if (dx + ox > width - image.attrs.width){
                    lx = dx + ox;
                }
                else{
                    lx = width - image.attrs.width;
                }
            }
            if (dy + oy <= 0){
                if (dy + oy > height - image.attrs.height){
                    ly = dy + oy;
                }
                else{
                    ly = height - image.attrs.height;
                }
            }

正向平移将允许图像向左和向下拖动。如果我们将转换限制为负值,它将停在左边和上边。对于右边和底边,我们将负平移限制为大于纸张宽度减去图像宽度的值。