【问题标题】:Svg Rotate and Resize issueSvg旋转和调整大小问题
【发布时间】:2013-06-13 01:20:35
【问题描述】:

我在 SVG 中工作,我被困在一个场景中,所以我需要一些快速帮助。这是小提琴中的工作演示

http://jsfiddle.net/5ekCa/

问题 我沿其中心以某个角度旋转了一个矩形,效果很好。然后我缩短矩形的宽度并再次旋转它。这一次它几乎没有错误旋转。我发现这是因为矩形的新中心点。我如何解决这个问题?矩形必须沿其新中心点旋转。

代码:

var rotate_rect = document.getElementById('rotate_rect');
var rectangle = document.getElementById('rectangle');
var angle = 0;

function calculateCenterXY(node) {
    var x = node.getBBox().x + (node.getBBox().width / 2);
    var y = node.getBBox().y + (node.getBBox().height / 2);

    var xy_co = {
        x: x,
        y: y
    };

    return xy_co;

}

function rotateMainRect() {

    var centxy = calculateCenterXY(rectangle);
    angle += 5;
    rotate_rect.setAttributeNS(null, 'transform', 'rotate(' + angle + ',' + centxy.x + ',' + centxy.y + ')');


}

function decreaseRectsize() {
    var newRectWidth = 50;
    rectangle.setAttribute('width', newRectWidth);
}

function RestoreRectsize() {
    var newRectWidth = 100;
    rectangle.setAttribute('width', newRectWidth);
}

HTML

<table>
    <tr>
        <td>
            <svg id="mainSvg" xmlns="http://www.w3.org/2000/svg" version="1.1" width="350" height="300">
                <g id="rotate_rect">
                    <rect id="rectangle" x="50" y="100" width="100" height="50" stroke="black" stroke-width="1" fill="black" />
                </g>
            </svg>
        </td>
        <td style="vertical-align: top">
            <button onclick="rotateMainRect()">Rotate +5 Angle</button>
        </td>
        <td style="vertical-align: top">
            <button onclick="decreaseRectsize()">Decrease Rect Size</button>
            <br/>
            <button onclick="RestoreRectsize()">Restore Rect Size</button>
        </td>
    </tr>
</table>

*注意:- 在小提琴中,在测试之前将 Js 加载选项更改为“无包裹体”

【问题讨论】:

    标签: javascript svg resize rotation


    【解决方案1】:

    小矩形的中心与大矩形的位置不同。小矩形实际上是大矩形的左半部分,因为您只是在更改宽度。调整矩形大小时,还需要重新定位它们,使它们的中心重合。

    function decreaseRectsize() {
        var newRectWidth = 50;
        rectangle.setAttribute('width', newRectWidth);
        rectangle.setAttribute('x', 75);
    }
    
    function RestoreRectsize() {
        var newRectWidth = 100;
        rectangle.setAttribute('width', newRectWidth);
        rectangle.setAttribute('x', 50);
    }
    

    【讨论】:

    • 感谢您的回复。这不是我要找的。我正在从事一个需要从一端调整矩形大小的项目。所以我不能像你上面那样改变 X 或 Y。
    • 我已经解决了这个问题。很快我将上传完整的 Demo 解决方案。
    • @RashFlash 我面临同样的问题。你能分享你的解决方案吗?非常感谢!
    猜你喜欢
    • 2021-09-18
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    相关资源
    最近更新 更多