Mouse position when moving an SVG object

3

In my JavaScript code, using the mouse I move an SVG rectangle from side to side. My problem is that when I click on the object, the mouse position is not fixed in the middle object but in the upper right corner and well outside the object. How can I position the mouse in the middle of the object?

My HTML:

<div id="divrect" onmousedown="start_drag(document.getElementById('divrect'), event);" style="position:absolute;" style="height:0px;"> 
        <svg  width="150" height="150"> 
            <rect id="rect" x="5" y="25" width="150" height="150" stroke="#0E0E0E" style="fill:red; stroke-width:1" />
             <text id =txtrect x="5" y="35" font-family="Verdana" font-size="11" fill="white" >
                Rect1
             </text>
        </svg> 
    </div>  

And my JavaScript code:

function start_drag(objet,event)
    {
        dragged = objet; 

        if( event.preventDefault ) event.preventDefault();
    }

    function drag_onmousemove(event)  
    {
      if( dragged ) 
      {
        x = event.clientX;
        y = event.clientY;
        dragged.style.position = 'absolute';
        dragged.style.left = x + 'px';
        dragged.style.top = y + 'px';
    }   
    
asked by anonymous 19.10.2014 / 13:09

1 answer

1

Well, you can get the height and width of the svg object, divide by 2, and subtract from your X and Y. This will result in your object located in the middle of the mouse pointer. Your JavaScript code looks like this:

function start_drag(objet,event) { 
    dragged = objet;
    if( event.preventDefault ) event.preventDefault();
}

function drag_onmousemove(event)  
{
    if( dragged ) 
    {
        x = event.clientX;
        y = event.clientY;
        elementHeight = dragged.clientHeight;
        elementWidth = dragged.clientWidth;
        dragged.style.position = 'absolute';
        dragged.style.left = x - elementWidth/2 + 'px';
        dragged.style.top = y - elementHeight/2 + 'px';
    }
}

The logic is that by dividing by half the value of length and height you will get the midpoints of your figure. Then, by subtracting the midpoints of the points from the current mouse position, you will result in the center points of your figure relative to the mouse position.

    
19.10.2014 / 16:45