bas*_*ent 5 html css svg viewbox zooming
我经常使用该viewBox
属性来“缩放”一个 SVG 元素。缩放当然是通过对属性使用较低的宽度和高度值来实现的viewBox
- 但是很难确定x和y值以保持场景居中。
下面是一个片段,其中viewBox="0 0 100 100"
. ( xy 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>
Run Code Online (Sandbox Code Playgroud)
(可在整页中查看。片段是响应式的)
改变宽度和高度值,以50
在viewBox
放大现场。但是,我必须将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>
Run Code Online (Sandbox Code Playgroud)
遵循将宽度和高度减半以使场景居中的模式:
viewBox="12.5 12.5 25 25"
应该继续缩放并保持居中。但它不会保持居中。我的问题是 SVG 使用什么公式或技术,我总能从数学上找出我需要什么x和y值来将特定的宽度和高度值放在viewBox
?
注意:我知道像Snap.svg和Raphaël这样的库。为了理解基本原理,我避免使用库。
另一件事:我问你是否已经在如何找到场景的中心坐标中具有宽度和高度值viewBox
。反之则不然。
外部样式表包括用于视觉认知。与此问题唯一相关的代码与 SVG 元素有关。
你的计算是错误的。如果宽度和高度viewBox
变小,则 x 和 y 值需要变大。
Initial viewBox: 0 0 100 100
Zoom X2: 25 25 50 50
Zoom X4: 37.5 37.5 25 25
Run Code Online (Sandbox Code Playgroud)
要获得 x 或 y 值,您需要从最后一个(或原始)viewBox 的中间点减去新宽度或高度的一半。
Zoom X2: centre - newWidth/2
= (100/2) - (50/2) = 25
Zoom X4: (100/2) - (25/2) = 37.5, or
(25 + 50/2) - (25/2) = 37.5
Run Code Online (Sandbox Code Playgroud)
计算它的另一种方法是从原始宽度中减去当前宽度并除以 2。
Zoom X4: (100 - 25) / 2 = 37.5
Run Code Online (Sandbox Code Playgroud)
Initial viewBox: 0 0 100 100
Zoom X2: 25 25 50 50
Zoom X4: 37.5 37.5 25 25
Run Code Online (Sandbox Code Playgroud)