首页 文章

在JS中,获取SVG路径的实际(计算)stoke-width

提问于
浏览
1

给定SVG路径元素的DOM节点,我如何以它为单位获得该路径的 stroke-width 's parent element? The goal is to add 2383255 to the path by adding additional elements to the parent of the path, whose dimensions are determined proportional to the path' s stroke-width . 路径的笔划宽度可以通过CSS,内联样式或可能影响笔划的任何其他方式来确定 .

我知道我可以得到计算出的样式值 window.getComputedStyle(node)['stroke-width'] . 但是返回包含单位的字符串 .

这些单位适用于哪种坐标系?我可以假设单位总是 px ,因此只需删除最后两个字符以获得数字吗?

1 回答

  • -2

    根据documentation getComputedStyle() 返回大多数属性所谓的computed values,它被定义为 px . 所以你可以尝试做类似的事情:

    var value = window.getComputedStyle(node)['stroke-width'];
    if (value.match(/^\-?\d+(\.\d+)px$/)) {
      value = parseFloat(value.substr(-2));
    } else {
      // Examine value further
    }
    

    我使用了 parseFloat 而不是 parseInt ,因为计算值可能是原始值的小数可能被定义为非px单位 .

相关问题