Mouse position when moving an SVG object

Asked

Viewed 88 times

3

In my Javascript code, using the mouse I move a 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 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';
    }   

1 answer

1


Well, you can take 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 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 when dividing by half the length and height value you will get the average points of your figure. Then, by subtracting the midpoints from the points of the current mouse position, you will have as a result the central points of your figure relative to the mouse position.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.