将元素缩放到像素大小

Scale element to pixel size

我有一个动态大小的 SVG 元素。我想按需将它及其内容 缩放到 特定像素大小(不是 像素)。

这是无效的:

transform: scale(100px);

我对 SVG 的了解一般,所以也许有更好的方法,但是在绘制内容后设置 SVG 元素的 height/width 只会导致其内容被破坏,因为它们是“绝对的”并且不是“相对”路径。

使用 JS,您可以获得相对大小:

const scaleX = targetWidth / svg.offsetWidth;
const scaleY = targetHeight / svg.offsetHeight;
svg.style.scale = `${scaleX}px ${scaleY}px`; //untested but you get the idea

我希望 CSS3 中某处有一种我不知道的“scaleTo”,或者是完成此操作的巧妙技巧。权威的“否”是可以接受的答案。

如果您有权访问 svg 的 html,则可以删除 svg 元素的宽度和高度属性,并将它们替换为具有 x/y 的 viewBox 属性位置设置为 0,width/height 对设置为您删除的值:

<svg width="300" height="200">
<!-- change to: -->
<svg viewBox="0 0 300 200">

然后您可以将 svg 元素放在一个大小 div 内,并将 svg 的 css 宽度和高度设置为 100%:

    .svgContainer svg {
      width: 100%;
      height: 100%;
    }

查看工作片段以比较效果,我将相同的 svg 压缩到一个较小的 div 中,有和没有 viewBox 集。

注意 对于动态调整大小,div 容器必须动态调整大小,viewBox 版本的 svg 设置为 100% 宽度和高度容器将自行处理。如果容器 Div 的大小是按 % 而不是像素,它会随着浏览器的视口增大和缩小。

如果您无法访问 html 标记,您可以使用 javascript 检索 svg 的 widthheight 属性并设置viewBox.

的新属性

关于 viewBox 的更多信息:https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/viewBox

.svgContainer {
  width: 100px;
}

.svgContainer svg {
  margin: 0;
  width: 100%;
  height: 100%;
}
<p> 300x200 svg rendered outside of a container:</p>
<svg width="300px" height="200px">
<rect x="0" y="0" width="100%" height="100%" fill="red" stroke="blue"/>
<rect x="100" y="50" width="100" height="50" fill="yellow"/>
<rect x="30" y="20" width="20" height="35" fill="blue"/>
</svg>

<p> same 300x200 svg rendered inside sized div:</p>
<div class="svgContainer">
<svg width="300px" height="200px">
<rect x="0" y="0" width="100%" height="100%" fill="red" stroke="blue"/>
<rect x="100" y="50" width="100" height="50" fill="yellow"/>
<rect x="30" y="20" width="20" height="35" fill="blue"/>
</svg>
</div>

<p>svg modified to use viewbox attribute values, inside sized div</p>
<div class="svgContainer">
<svg viewBox="0 0 300 200">
<rect x="0" y="0" width="100%" height="100%" fill="red" stroke="blue"/>
<rect x="100" y="50" width="100" height="50" fill="yellow"/>
<rect x="30" y="20" width="20" height="35" fill="blue"/>
</svg>
</div>