0

I know that I can obtain it with the width or size function, but I'm trying to do it in the moment of the creation of a draggable object.

I'm doing this because I need to give a grid effect to the element and also make it stay inside the drawable area.

Here is something similar to what I'm trying to do:

square = draw.rect(size, size).x(x).y(y).draggable(function(x, y){
var xend = x - x % size;
var yend = y - y % size;

if(xend < 0)
    xend = 0;
if(yend < 0)
    yend = 0;

if(xend > 1000)
    xend = 1000 - width*;

return { x: xend, y: yend } 
});

The var with an * is what I want to get.

Also would be great to know how to allow svg.js elements interact with jquery, but I guess that's for another question.


Edit: Well, now in fact I need to access to other properties of the element, if I can't do that from the draggable element I think I should look for another way to make it draggable? :( please help!

Felix
  • 579
  • 1
  • 8
  • 23
  • Well, I finally did it. I did use the **SVG.get()** function. Later I will comment the answer in order to show how can be done. – Felix Jun 27 '14 at 04:35
  • You can just use square.box().width in the function. If the width does not change you should cache it for performance. Using SVG.get is that situation is far from optimal in a performance point of view. – Nils Jun 27 '14 at 17:14
  • Sadly nope, javascript just throws square.box is not a function – Felix Jun 28 '14 at 21:51
  • Sorry, it should be square.bbox(). I'm traveling and writing on my cell. – Nils Jun 29 '14 at 07:03

2 Answers2

0

The solution is (as Nils said), use the square.bbox function, for example:

square = draw.rect(size, size).x(x).y(y).draggable(function(x, y){
var xend = x - x % size;
var yend = y - y % size;

if(xend < 0)
    xend = 0;
if(yend < 0)
    yend = 0;

if(xend > 1000)
    xend = 1000 - square.bbox().width;

return { x: xend, y: yend } 
});

Also, if you want to access to the element later you can assign an id with the square.attr('id','id_name') method and call using the SVG.get('id_name') method.

Felix
  • 579
  • 1
  • 8
  • 23
0

You may interested in the fact, that the callback of the draggable-function is called in the scope of the element itself. Furthermore there is no need to use bbox here because the width is stored as attribute in the element.

So the solution would be:

square = draw.rect(size, size).x(x).y(y).draggable(function(x, y){
    var xend = x - x % size;
    var yend = y - y % size;

    if(xend < 0)
        xend = 0;
    if(yend < 0)
        yend = 0;

    if(xend > 1000)
        xend = 1000 - this.attr('width')

    return { x: xend, y: yend } 
});

Btw: Why are you searching for the width and using size a few lines above? Its the same value because you just set the width to size

Fuzzyma
  • 7,619
  • 6
  • 28
  • 60