首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

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

在SVG中制作条形图和动画条形图向上增长,可以通过以下步骤实现:

  1. 创建SVG元素 首先,创建一个SVG元素,并设置其宽度和高度。例如:<svg width="500" height="300" id="bar-chart"></svg>
  2. 添加条形图 接下来,为每个数据点创建一个矩形元素,并设置其宽度、高度、颜色等属性。例如:const data = [10, 20, 30, 40, 50]; const barWidth = 40; const barGap = 5; const bars = data.map((value, index) => { const bar = document.createElementNS('http://www.w3.org/2000/svg', 'rect'); bar.setAttribute('x', index * (barWidth + barGap)); bar.setAttribute('y', 0); bar.setAttribute('width', barWidth); bar.setAttribute('height', 0); bar.setAttribute('fill', 'steelblue'); return bar; }); document.getElementById('bar-chart').appendChild(...bars);
  3. 添加动画效果 为每个矩形元素添加动画效果,使其从底部向上增长。例如:bars.forEach((bar, index) => { const animation = document.createElementNS('http://www.w3.org/2000/svg', 'animate'); animation.setAttribute('attributeName', 'height'); animation.setAttribute('from', 0); animation.setAttribute('to', data[index]); animation.setAttribute('dur', '1s'); animation.setAttribute('begin', `${index * 0.5}s`); bar.appendChild(animation); });
  4. 完整代码 将以上代码整合在一起,即可实现条形图的动画效果。完整代码如下:<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>SVG条形图动画</title> </head> <body> <svg width="500" height="300" id="bar-chart"></svg> <script> const data = [10, 20, 30, 40, 50]; const barWidth = 40; const barGap = 5; const bars = data.map((value, index) => { const bar = document.createElementNS('http://www.w3.org/2000/svg', 'rect'); bar.setAttribute('x', index * (barWidth + barGap)); bar.setAttribute('y', 0); bar.setAttribute('width', barWidth); bar.setAttribute('height', 0); bar.setAttribute('fill', 'steelblue'); return bar; }); document.getElementById('bar-chart').appendChild(...bars); bars.forEach((bar, index) => { const animation = document.createElementNS('http://www.w3.org/2000/svg', 'animate'); animation.setAttribute('attributeName', 'height'); animation.setAttribute('from', 0); animation.setAttribute('to', data[index]); animation.setAttribute('dur', '1s'); animation.setAttribute('begin', `${index * 0.5}s`); bar.appendChild(animation); }); </script> </body> </html>

这样,就可以在SVG中制作条形图,并实现动画效果。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券