KineticJS中的约束/比例缩放

时间:2012-12-15 16:25:44

标签: javascript jquery html5 canvas kineticjs

当拖动图像的4个角手柄中的任何一个时,图像应按比例向上或向下缩放。

问题:根据我在下面链接的jsfiddle中显示的当前尝试,当topLeft句柄垂直拖动时,图像按比例重新缩放,但另一个处理闪烁。当水平拖动相同的topLeft手柄时,图像只会移动而不会调整大小。

如何使用KineticJS实现比例缩放?谢谢!!!

jsfiddle: http://jsfiddle.net/zb3Km/

1 个答案:

答案 0 :(得分:3)

顺便这样.....
math/algorithm Fit image to screen retain aspect ratio

我得到了这个......

function update(group, activeAnchor) {
    var topLeft     = group.get(".topLeft")[0];
    var topRight     = group.get(".topRight")[0];
    var bottomRight = group.get(".bottomRight")[0];
    var bottomLeft     = group.get(".bottomLeft")[0];
    var image         = group.get(".image")[0];

    // update anchor positions
    switch(activeAnchor.getName()) {
        case "topLeft":

            topRight.attrs.y = activeAnchor.attrs.y;
            //topRight.attrs.x = activeAnchor.attrs.x + image.getWidth();
            bottomLeft.attrs.x = activeAnchor.attrs.x;
           // bottomRight.attrs.x = activeAnchor.attrs.x + image.getWidth();

            break;
        case "topRight":
            topLeft.attrs.y = activeAnchor.attrs.y;
            bottomRight.attrs.x = activeAnchor.attrs.x;
            break;
        case "bottomRight":
            bottomLeft.attrs.y = activeAnchor.attrs.y;
            topRight.attrs.x = activeAnchor.attrs.x;
            break;
        case "bottomLeft":
            bottomRight.attrs.y = activeAnchor.attrs.y;
            topLeft.attrs.x = activeAnchor.attrs.x;
            break;
    }

    //https://stackoverflow.com/questions/6565703/math-algorithm-fit-image-to-screen-retain-aspect-ratio

    var ws= topRight.attrs.x - topLeft.attrs.x;
    var hs = bottomLeft.attrs.y - topLeft.attrs.y;
    var wi =   image.getWidth();
    var hi = image.getHeight();
    var rs = ws/hs;
    var ri = wi/hi;
    if (rs>ri){
        var width =wi * hs/hi;
        image.setSize(width, hs);
        image.setPosition( topLeft.attrs.x+((ws-width)/2), bottomLeft.attrs.y-((hi)));

    } else {
        var height=hi * ws/wi;
        image.setSize(ws, height);
         image.setPosition( topRight.attrs.x-wi, topLeft.attrs.y+((hs-height)/2));
    }


}

http://jsfiddle.net/zb3Km/2/
编辑:
http://jsfiddle.net/zb3Km/3/
完成大小调整后,锚点会重新弹回

EDIT2: 现在将调整大小锚定到对面的角落 http://jsfiddle.net/jdA3y/