我正在将条形图制作为 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>
这看起来像条形图,因为 (y + height) 对于所有矩形都是相同的,但它在概念上是“从上到下”绘制的,从 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>
这将使矩形从 y=8“向下”增长到 y=22,并且在网格中(0,0)位于左上角,这非常有意义。但是,我真的想做相反的事情,因为“高度”属性的负值似乎被视为 0(或者我可以将高度从 -14 设置为 0)我不确定我会怎么做。
我试过谷歌搜索,但运气不佳。我也非常想在不使用图表库的情况下执行此操作。
最佳答案
如果你用 scale(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>
请注意,您需要将所有 y 值设置为相等,并且您可能想要翻转渐变。
关于svg - 如何使 SVG 中的条形图具有向上增长的动画条形图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11815207/