简体   繁体   中英

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

I created a vector image and set the width and height percent to 100%, like that:

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%');

Now I want to create a rectangle with the position of '100% - 20px' but it doesn't work, because 100% is not a number. How could I resolve this issue?

To achieve this you can use calc() . This will let you perform calculations when specifying CSS property values.

So your code should be something like this:

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%');

NOTE: Keep in mind, you can't use calc(100% - 20px) for height in your particular case because the result will be unknown. So it's better to use calc(100vh - 20px) or 100% itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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