如何在SVG中制作条形图,动画条形图向上增长?

iva*_*rni 1 svg

我正在制作一个条形图作为SVG,并且非常希望我的条形图被动画化并从y轴上的"0"向上增长到它们的相应值.

令我挣扎的是,坐标(0,0)位于左上角而不是左下角.在我的"非动画"解决方案中,我给了条形码"y"的不同值取决于它们应该有多高,如下所示:

<svg id="graph" 
        xmlns="http://www.w3.org/2000/svg" 
        xlink="http://www.w3.org/1999/xlink">
    <linearGradient x1="0%" x2="0%" y1="10%" y2="100%" id="gradient">
        <stop style="stop-color:#0000FF" offset="0"></stop>
        <stop style="stop-color:#FFFFFF" offset="1"></stop>
    </linearGradient>
    <rect width="50" height="14" x="0" y="8" fill="url(#gradient)"></rect>
    <rect width="50" height="22" x="55" y="0" fill="url(#gradient)"></rect>
    <rect width="50" height="15" x="110" y="7" fill="url(#gradient)"></rect>
    <rect width="50" height="9" x="165" y="13" fill="url(#gradient)"></rect>
</svg>
Run Code Online (Sandbox Code Playgroud)

这看起来像条形图,因为(y +高度)对于所有矩形都是相同的,但它在概念上从y轴的不同点开始"从上到下"绘制并向下生长到y的相同值.

现在当我想要动画时,我显然希望它们"向上"增长,这就是我被困住的地方.

<rect width="50" height="14" x="0" y="8" fill="url(#gradient)">
    <animate attributeName="height" from="0" to="14" dur="2s" id="animation"></animate>    
</rect>
Run Code Online (Sandbox Code Playgroud)

这将使矩形从y = 8变为"向下"到y = 22并且在网格中,其中(0,0)在左上方,这是完全有意义的.但是,我真的想要做相反的事情,因为看起来"height"属性的负值被视为0(或者我可以将高度从-14设置为0)我不确定我将如何做到这一点.

我试过谷歌搜索但没有太多运气.我也非常喜欢这样做而不使用图表库.

Pet*_*dge 5

如果用缩放(1,-1)变换包装所有内容,则所有y值都乘以-1,这会产生翻转y轴的效果.然后,您需要将所有内容翻译下来,以便它们具有正值,您可以看到它们:

<g transform="translate(0, 40) scale(1, -1)">    
  <rect width="50" height="14" x="0" y="0" fill="url(#gradient)">
    <animate attributeName="height" from="0" to="14" dur="2s" fill="freeze"></animate>    
  </rect>
  <rect width="50" height="14" x="55" y="0" fill="url(#gradient)">
    <animate attributeName="height" from="0" to="22" dur="2s" fill="freeze"></animate>    
  </rect>
  <rect width="50" height="14" x="110" y="0" fill="url(#gradient)">
    <animate attributeName="height" from="0" to="15" dur="2s" fill="freeze"></animate>    
  </rect>
  <rect width="50" height="14" x="165" y="0" fill="url(#gradient)">
    <animate attributeName="height" from="0" to="9" dur="2s" fill="freeze"></animate>
  </rect>
</g>
Run Code Online (Sandbox Code Playgroud)

请注意,您需要将所有y值设置为相等,并且可能需要翻转渐变.