【问题标题】:Scale an line svg as per height of the container根据容器的高度缩放线条 svg
【发布时间】:2021-02-12 23:16:17
【问题描述】:

我正在制作一个 svg(线元素),它是垂直的。我希望该 svg 线根据容器的高度进行缩放。

<div class="parent">
    <svg viewBox="0 0 100 100">
       <line x1="0" y1="0" x2="0" y2="20" style="stroke: black;stroke-width:1"/>
    </svg>
</div>

现在如果增加父级宽度,垂直线的高度会缩放,但要求是,随着高度的增加,长度应该按比例增加。 我把viewBox 写错了吗?

【问题讨论】:

    标签: javascript html css svg


    【解决方案1】:

    我认为您正在寻找vector-effect 属性。如果您将其设置为non-scaling-stroke - 这将使您能够将线条的笔划保持在 1 个像素,而与 svg 的大小无关。看看下面这个例子,我已经设置了 svg 来填充父对象:

    .parent {
      background: #efefef;
      width: 200px;
      height: 200px;
    }
    
    svg {
      width: 100%;
      height: 100%;
    }
    <div class="parent">
        <svg viewBox="0 0 100 100">
           <line x1="0" y1="0" x2="0" y2="100" 
             style="stroke: black;stroke-width:1" 
             vector-effect="non-scaling-stroke"/>
        </svg>
    </div>

    尝试改变父母周围的大小,你会发现笔触宽度始终保持一致。

    【讨论】:

    • 真的很有帮助,谢谢!!我不得不更新 viewbox = 0 0 0 100。
    【解决方案2】:

    按比例缩放 SVG:

    .parent {
      background: yellow;
    }
    
    .parent svg {
      height: 100%;
    }
    100px height
    <div class="parent" style="height: 100px;">
        <svg  viewBox="0 0 2 100" preserveAspectRatio="none">
           <line x1="0" y1="0" x2="0" y2="100" style="stroke: black; stroke-width:2"/>
        </svg>
    </div>
    300px height
    <div class="parent" style="height: 300px;">
        <svg  viewBox="0 0 2 100" preserveAspectRatio="none">
           <line x1="0" y1="0" x2="0" y2="100" style="stroke: black; stroke-width:2"/>
        </svg>
    </div>

    缩放 SVG 但保持笔画

    .parent {
      background: yellow;
    }
    
    .parent svg {
      height: 100%;
    }
    100px height
    <div class="parent" style="height: 100px;">
        <svg  viewBox="0 0 2 100" preserveAspectRatio="none">
           <line x1="0" y1="0" x2="0" y2="100" style="stroke: black; stroke-width:2" vector-effect="non-scaling-stroke"/>
        </svg>
    </div>
    300px height
    <div class="parent" style="height: 300px;">
        <svg  viewBox="0 0 2 100" preserveAspectRatio="none">
           <line x1="0" y1="0" x2="0" y2="100" style="stroke: black; stroke-width:2" vector-effect="non-scaling-stroke"/>
        </svg>
    </div>

    【讨论】:

    • 当你增加高度时笔画宽度增加
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 2015-09-23
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    相关资源
    最近更新 更多