javascript – Mouse position when moving an SVG object

Question:

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 place the mouse in the middle of the object?

My HTML code:

<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';
    }   

Answer:

Well, you can take the height and width of the svg object, divide it by 2 and subtract it from its X and Y. This will result in your object located in the middle of the mouse pointer. Your JavaScript code would look 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 halving the length and height value you will get the midpoints of your figure. So, by subtracting the midpoints of the points of the current mouse position, you will have as a result the center points of your figure in relation to the mouse position.

Scroll to Top