我有一个复杂的SVG图形,它是交互式的。在该图形中有一个特定的图标,让我们说它是信息图中的特定人物图标。此外,SVG是2000x2000像素。这意味着在桌面(横向布局)上,它需要从顶部和底部剪切一些可能使其适合屏幕。在移动设备(纵向模式)中,它需要从右侧和左侧剪掉一些。鉴于此,我希望SVG以该人为中心,并以横向模式剪切顶部/底部,并以纵向模式剪辑左/右。这实现了两个目标:
想知道如何做到这一点。如果它必须用JavaScript完成,或者它可以完全用CSS完成。
此外,此SVG无法加载到CSS的背景图像中,因为它是交互式的。这是普通的SVG。
为了简化问题,我们可以说我们有一堆嵌套元素的<div>
。我们希望这个div基于它包含的一些嵌套元素来居中。所以这似乎需要某种JavaScript。也就是说,在窗口调整大小或方向改变时,获取我们想要居中的元素的偏移量,然后弄清楚如何调整它居中,然后从中找出如何调整parent.parent.parent ...等。直到你到达你希望锚定在那个点的主包装div。然后我们只是移动那个div。所以看起来这需要JavaScript,但我不知道,也许有一种方法可以通过纯CSS实现这一点。
想知道是否可以在JS或CSS中演示如何执行此操作。
这是我到目前为止所拥有的。
// the box should be centered in the screen
<!doctype html>
<html>
<head>
<style>
html, body {
margin: 0;
padding: 0;
overflow: hidden;
width: 100vw;
height: 100vh;
}
svg {
display: block;
}
@media (orientation: landscape) {
svg {
width: 100vw;
height: auto;
}
}
@media (orientation: portrait) {
svg {
width: auto;
height: 100vh;
}
}
</style>
</head>
<body>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2000 2000">
<rect width='100' height='100' x="1000" y="1000" />
</svg>
</body>
</html>
请注意移动设备(https://imgur.com/PnugEin)如何正确填充空间。黑匣子应始终位于中心,整个SVG应缩放,以覆盖整个视口,同时将黑匣子保持在中心位置。
更新:好的通过添加媒体查询找出“填充视口”问题。最后一件事是如何根据矩形/锚点使其居中。
要使矩形居中,您需要用半个width
或height
来抵消它。在这种情况下,您可能需要翻译矩形。做这个:
html,
body {
margin: 0;
padding: 0;
overflow: hidden;
width: 100%;
height: 100%
}
<svg width="100%" height="100%">
<rect width='100%' height='100%' x="0" y="0" fill="yellow" />
<rect width='100' height='100' x="50%" y="50%" transform="translate(-50,-50)" fill="green" />
</svg>
试试这个:
svg[viewBox="0 0 2000 2000"] {
/* center the SVG in the viewport */
position: absolute;
top: -50%;
bottom: -50%;
left: -50%;
right: -50%;
margin: auto;
/* offsets from center of SVG. In the example given, it's (100/2)/2000 and then multiply by 100 because it's a percentage */
-webkit-transform: translate(-2.5%,-2.5%);
transform: translate(-2.5%,-2.5%);
}