Resize JavaScript with aspect ratio

I am writing a little script that allows the user to move and resize the div. I need to keep aspect ratio and my logic is not working.

function resizing() {
    var currentHeight = elmnt.offsetHeight;
    var currentWidth  = elmnt.offsetWidth;
    var newHeight     = currentHeight + (event.pageY - currentY);
    var newWidth      = currentWidth  + (event.pageX - currentX);
    var ratio         = currentWidth  / currentHeight;

    if(ratio < 1) {
        newwidth = parseInt(newHeight * ratio);
    }
    else {
        newheight = parseInt(newWidth / ratio);
    }

    elmnt.style.height = newHeight + "px";
    elmnt.style.width  = newWidth  + "px";

    currentY = event.pageY;
    currentX = event.pageX;
}

Job script. But, unfortunately, it does not fully support the aspect ratio. Sometimes, when I change only horizontally, the old height remains unchanged, sometimes it works, but one length changes with a slight shift.

When I resize up and down and again and again, the lengths become more and more equal, and when it is the right square, everything is correct.

Hwo can I fix my problems? Where is my mistake ?!

0
source share
4

.

!

, , . , , , BIG .

css jQuery . .

, . .

onclick , :

currentHeight = $("#dragger").height();
currentWidth = $("#dragger").width();

! : http://jsfiddle.net/julian_weinert/xUAZ5/30/

+1

, .

, / .

.

var ratio = newWidth / currentWidth;
newHeight = currentHeight * ratio;

, , .

0

, (). PHP script, JS. $iSrc= $iDest - / MAX .

, . - , . . / /. .

$scale = min($iDestWidth/$iSrcWidth, $iDestHeight/$iSrcHeight);

    if($scale >= 1){
        $iDestHeight = $iSrcHeight;
        $iDestWidth = $iSrcWidth;
    }else{          
        $iDestWidth = floor($scale*$iSrcWidth);
        $iDestHeight = floor($scale*$iSrcHeight);
    }
0
source

replace the if (ratio <1) block as follows. offsetx and offset relate to your (event.pageX - currentX) and (event.pageY - currentY):

if (Math.abs(offsetx) > Math.abs(offsety)) {
    ratio = currentHeight/currentWidth;
    newHeight = currentHeight + (offsetx * ratio);
    newWidth = currentWidth + offsetx;        
} else {
    ratio = currentWidth/currentHeight;
    newHeight = currentHeight + offsety;
    newWidth = currentWidth + (offsety * ratio);  
}

Here is a brief description of the whole thing in action: http://jsfiddle.net/8TWRV/

0
source

All Articles