Constrained/Proportional Scaling in KineticJS

我怕爱的太早我们不能终老 提交于 2019-12-06 16:02:40

问题


When any of the 4 corner handles of the image is dragged, the image should scale proportionally either up or down.

Problem: With my current attempt as shown in the jsfiddle linked below, when the topLeft handles are dragged vertically, the image rescales proportionally, but the other handles flicker. When the same topLeft handle is dragged horizontally, the image simply moves without resizing.

How can proportional scaling be implemented with KineticJS? Thank you!!!

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


回答1:


Going by this.....
math/algorithm Fit image to screen retain aspect ratio

I got this.....

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/
EDIT:
http://jsfiddle.net/zb3Km/3/
Made the anchors snap back after your finished resizing

EDIT2: Now anchors the resize to the opposite corner.
http://jsfiddle.net/jdA3y/



来源:https://stackoverflow.com/questions/13893966/constrained-proportional-scaling-in-kineticjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!