通常我使用viewBox
属性来“缩放”SVG元素。当然,通过使用较低的width和height值来设置viewBox
属性实现缩放 - 但是对于保持场景居中,x和y值有点棘手。
下面是一个片段,其中viewBox="0 0 100 100"
。( x y width height )这是我的起点。场景按比例缩放并从左上角开始。
<head>
<link rel="stylesheet" href="https://codepen.io/basement/pen/oepKxY.css">
</head>
<body>
<iframe src="https://s.codepen.io/basement/debug/zdpVyV/PNAvYLZmJRQr"
id="grid"
></iframe>
<div class="wrp">
<!-- SVG relevant code below-->
<svg xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 100 100"
width="100" height="100"
class="canvas"
>
<defs>
<style type="text/css">
circle {
fill: #0ff;
fill-opacity: 0.25;
stroke-width: 0.25;
stroke: #0ee;
}
</style>
</defs>
<circle cx="37.5" cy="50" r="25" />
<circle cx="62.5" cy="50" r="25" />
<circle cx="50" cy="71.65" r="25" />
</svg>
</div>
</body>
(可以在完整页面中查看。代码片段具有响应性)
缩放
将viewBox
中的宽度(width)和高度(height)值更改为50
,即可将场景缩放。但是,我不得不同时调整x
和y
的值,使其都为viewBox
的一半尺寸:25
,以保持图形居中。
viewBox="25 25 50 50"
<head>
<link rel="stylesheet" href="https://codepen.io/basement/pen/oepKxY.css">
</head>
<body>
<iframe src="https://s.codepen.io/basement/debug/zdpVyV/PNAvYLZmJRQr"
id="grid"
></iframe>
<div class="wrp">
<!-- SVG relevant code below-->
<svg xmlns="http://www.w3.org/2000/svg"
viewBox="25 25 50 50"
width="100" height="100"
class="canvas"
>
<defs>
<style type="text/css">
circle {
fill: #0ff;
fill-opacity: 0.25;
stroke-width: 0.25;
stroke: #0ee;
}
</style>
</defs>
<circle cx="37.5" cy="50" r="25" />
<circle cx="62.5" cy="50" r="25" />
<circle cx="50" cy="71.65" r="25" />
</svg>
</div>
</body>
减半宽度和高度不一致
按照减半宽度和高度的模式来居中场景:
viewBox="12.5 12.5 25 25"
应继续缩放并保持居中。但它并没有保持居中。我的问题是SVG使用了什么公式或技术,我可以始终数学计算出要在viewBox
中居中特定宽度和高度值所需的x和y值。
注意:我知道有像Snap.svg和Raphaël这样的库。为了理解基本原理,我避免使用库。
还有一件事:如果你已经在viewBox
中有一个宽度和高度值,如何找到场景的中心坐标。反之亦然。
外部样式表是为视觉认知而包含的。这个问题唯一相关的代码与SVG元素有关。
(35,67)
和一个缩放级别,例如2X50 50
在这种情况下,如何调整此公式,然后得出X和Y坐标以使该点(35,67)
保持在viewBox的中心?这里有一个关于此问题的完整未解答(并最近已编辑)的问题:https://stackoverflow.com/questions/45892233/centering-on-specific-points-when-zooming-using-svg-viewbox?noredirect=1&lq=1 - basementviewBox
。你的解决方案很可靠,在这种情况下再次起作用。谢谢! - basement