【发布时间】:2018-02-04 03:26:36
【问题描述】:
我经常使用viewBox 属性来“缩放” SVG 元素。缩放当然是通过对viewBox 属性使用较低的 width 和 height 值来完成的 - 但 x 和 y em> 值很难确定以保持场景居中。
下面是一个sn-p,其中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>
宽度和高度减半不一致
按照将 width 和 height 减半的模式使场景居中:
viewBox="12.5 12.5 25 25" 应该继续缩放并保持居中。但它不会保持居中。我的问题是 SVG 使用什么公式或技术,我总能从数学上算出我需要使特定 width 居中的 x 和 y 值是多少viewBox?中的 height 值?
注意:我知道像 Snap.svg 和 Raphaël 这样的库。为了理解基本原理,我避免使用库。
还有一件事:我在问你是否在viewBox 中已经有了 width 和 height 值,你如何找到中心坐标现场。反之亦然。
为了视觉认知,包含了外部样式表。这个问题唯一相关的代码是关于 SVG 元素的。
【问题讨论】:
标签: html css svg zooming viewbox