简体   繁体   中英

How to set font-size for svg without unit in javascript

I'm editing plotly.js library source code to have scalable plots, I set viewBox and preserveAspectRatio (plotly.js use d3 library) but have problem with font-size if I use no unit the property get changed to px

I've tried to test from console if font is changed to have no unit using this:

[...document.querySelectorAll('text')].forEach((text) => {
    text.style.fontSize = text.style.fontSize.replace('px', '')
});

but it seems that if you don't use unit, the px is added automatically.

I've also tried to use rem unit and set 62.5% on html where original font size is divided by 10 but it don't scale when I resize the plot.

Also tried this new CSS typed OM API:

[...document.querySelectorAll('text')].forEach((text) => {
   var size = +text.style.fontSize.replace('px', '');
   text.attributeStyleMap.set('font-size', CSS.number(size))
});

but got error:

Failed to execute 'set' on 'StylePropertyMap': Invalid type for property

Any solution to have font-size without unit set from javascript, or other way to proportional text?

in svg each style property have corresponding attribute so you can use:

d3.select('text').attr('font-size', 10);

and it will set font-size without unit. The plot still don't scale but this was the question.

In SVG, having no units specifier is the same as using px . So font-size: 10 and font-size: 10px mean the same. They will behave the same.

I don't know why it matters to you that the value has no units. It sounds like you think that it is why your text is not scaling. That will not be why. There must be something else going on. If you want help with that problem, then add a MCVE to your question.

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