You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SVG柱状图动画求助:实现条形从0增长至目标高度

解决SVG柱状图从底部增长的动画问题

你之前用animateTransform的scale动画出现异常,是因为SVG默认的transform-origin是元素左上角,导致缩放时从左上角开始变形。下面给两种可行的解决方案:

方法1:直接动画矩形的height和y属性

SVG矩形的y坐标对应顶部位置,要实现从底部往上增长,需要让y从容器底部(总高度)移动到目标顶部位置,同时height从0增加到目标高度。示例代码:

<svg width="400" height="300" viewBox="0 0 400 300">
  <!-- 背景网格/坐标轴可自行添加 -->
  <!-- 条形1:目标高度150,从底部(y=300)增长到y=150 -->
  <rect x="50" y="300" width="60" height="0" fill="#4CAF50">
    <animate attributeName="height" from="0" to="150" dur="4s" fill="freeze" />
    <animate attributeName="y" from="300" to="150" dur="4s" fill="freeze" />
  </rect>
  <!-- 条形2:目标高度200 -->
  <rect x="130" y="300" width="60" height="0" fill="#2196F3">
    <animate attributeName="height" from="0" to="200" dur="4s" fill="freeze" />
    <animate attributeName="y" from="300" to="100" dur="4s" fill="freeze" />
  </rect>
  <!-- 条形3:目标高度100 -->
  <rect x="210" y="300" width="60" height="0" fill="#FF9800">
    <animate attributeName="height" from="0" to="100" dur="4s" fill="freeze" />
    <animate attributeName="y" from="300" to="200" dur="4s" fill="freeze" />
  </rect>
</svg>

这种方式逻辑直观,不需要处理变换原点,兼容性也更好。

方法2:修正scale动画的变换原点

如果坚持用animateTransform的scale动画,只需给每个条形设置transform-origin为底部中心,让缩放从底部开始:

<svg width="400" height="300" viewBox="0 0 400 300">
  <rect x="50" y="150" width="60" height="150" fill="#4CAF50" transform-origin="50% 100%">
    <animateTransform attributeName="transform" type="scale" from="1 0" to="1 1" dur="4s" fill="freeze" />
  </rect>
  <rect x="130" y="100" width="60" height="200" fill="#2196F3" transform-origin="50% 100%">
    <animateTransform attributeName="transform" type="scale" from="1 0" to="1 1" dur="4s" fill="freeze" />
  </rect>
</svg>

transform-origin="50% 100%"表示以矩形的水平中心、垂直底部为变换原点,这样scaleY从0到1时,条形会从底部向上拉伸,不会出现飞入的异常效果。

内容的提问来源于stack exchange,提问作者vikavenable

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 07:09:57