繁体   English   中英

如何将 SVG 的宽度从百分比转换为像素?

[英]How can I convert the width of SVG from percent to pixel?

我创建了一个矢量图像并将宽度和高度百分比设置为 100%,如下所示:

var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
var svgNS = svg.namespaceURI;
svg.setAttribute('id', 'idsvg');
svg.setAttribute('width', '100%');
svg.setAttribute('height', '100%');

现在我想用 '100% - 20px' 的 position 创建一个矩形,但它不起作用,因为 100% 不是数字。 我该如何解决这个问题?

为此,您可以使用calc() 这将允许您在指定 CSS 属性值时执行计算。

所以你的代码应该是这样的:

var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
var svgNS = svg.namespaceURI;
svg.setAttribute('id', 'idsvg');
svg.setAttribute('width', 'calc(100% - 20px)');
svg.setAttribute('height', '100%');

注意:请记住,在您的特定情况下,您不能使用calc(100% - 20px)作为height ,因为结果将是未知的。 所以最好使用calc(100vh - 20px)100%本身。

暂无
暂无

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

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