简体   繁体   English

用适当的viewBox值替换width和height属性

[英]Replacing width and height properties with proper viewBox values

This question is helpful in understanding the purpose of viewBox, but isn't quite the same. 这个问题有助于理解viewBox的目的,但并不完全相同。

The goal is to replace the width and height properties of an SVG element with a corresponding viewBox property. 目标是用相应的viewBox属性替换SVG元素的width和height属性。 Our code requires viewBox to be set, and not width and height. 我们的代码要求设置viewBox,而不是width和height。

Is there an algorithmic way of doing this? 有算法的方法可以做到这一点吗?

For instance, the SVG element below when replaced with a viewBox property of 0 0 6 6 does not look the same. 例如,当下面的SVG元素替换为viewBox属性0 0 6 6时,看起来并不相同。

Original 原版的

 <svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' width='6' height='6'> <rect width='6' height='6' fill='#eee'/> <g id='c'> <rect width='3' height='3' fill='#e6e6e6'/> <rect y='1' width='3' height='2' fill='#d8d8d8'/> </g> <use xlink:href='#c' x='3' y='3'/> </svg> 

Edited 编辑

 <svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox="0 0 6 6"> <rect width='6' height='6' fill='#eee'/> <g id='c'> <rect width='3' height='3' fill='#e6e6e6'/> <rect y='1' width='3' height='2' fill='#d8d8d8'/> </g> <use xlink:href='#c' x='3' y='3'/> </svg> 

Sandbox https://jsbin.com/micepar/embed?html,output 沙盒 https://jsbin.com/micepar/embed?html,输出

TL;DR: You can't, that's not what viewBox does. TL; DR:您不能,那不是viewBox要做的。

An SVG canvas can be considered to be an infinite drawing surface. 可以将SVG画布视为无限绘图表面。 viewBox tells the browser which part should be visible. viewBox告诉浏览器哪个部分应该可见。 This visible area will be scaled and positioned to fit the element's content area. 该可见区域将被缩放并定位为适合元素的内容区域。 The defaults for viewBox are usually such that x and y are 0 while width and height match the element's pixel dimensions. viewBox的默认值通常为x和y为0,而width和height匹配元素的像素尺寸。 However, viewBox does not change those dimensions. 但是, viewBox不会更改这些尺寸。

An SVG element's height and width change the element's content area. SVG元素的高度和宽度会更改元素的内容区域。 The viewBox area is scaled to fit this content area. 缩放viewBox区域以适合此内容区域。 If height and width are not set, they will be some convenient size depending on browser implementation and are not dependent on viewBox even if they appear to be in certain situations. 如果未设置高度和宽度,则它们的大小将取决于浏览器的实现,并且即使在某些情况下也不取决于viewBox

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM