[英]Animating bar in canvas
因此,我正在尝试创建一个动画图表,该图表中的一个栏从下到上都是动画的。 问题是当我运行它时,仅显示一个没有动画的栏。 有人可以帮忙吗?
编码:
let canvas = document.getElementById('chart');
let ctx = canvas.getContext('2d');
let values = config().data;
let width = config().width;
let spaceBetweenBars = config().spaceBetweenBars;
let startingX = 50;
canvas.height = 300;
canvas.width = 400;
ctx.fillStyle = config().color;
for (let i = 0; i < values.length; i++) {
let height = values[i];
let l = 0;
while(l < height){
setTimeout(()=>{
ctx.fillRect(startingX, canvas.height - height, width, l)
},1000)
l++;
}
startingX += width + spaceBetweenBars;
}
由于您没有给我config()
的结果,因此我发明了一个config
对象。
我已经尝试过按照您想要的方式进行操作。 我会以不同的方式组织数据。
为了使条requestAnimationFrame
起来,我使用了requestAnimationFrame
因为它效率更高。 如果愿意,可以改用setInterval()
。
请阅读我的代码中的注释。
let canvas = document.getElementById('chart'); let ctx = canvas.getContext('2d'); canvas.height = 150; canvas.width = 400; let config = {width:30,height:0,spaceBetweenBars:5,color:"green"}; let values = [35,48,98,34,55]; // copy the values array and fill it with 0. // This is the value of bars height during the animation let currentValues = values.slice().fill(0); // [0,0,0,0,0] let startingX = 50; function drawBar(height,i){ let x = startingX; x += i*(config.width + config.spaceBetweenBars); ctx.fillStyle = config.color; ctx.beginPath(); ctx.fillRect(x, canvas.height, config.width, -height); } // I'm using requestAnimationFrame since it's much more efficient. function drawChart(){ window.requestAnimationFrame(drawChart); for(let i = 0; i < values.length;i++) { if(currentValues[i] < values[i]){ currentValues[i] ++; drawBar(currentValues[i],i) } } } drawChart()
canvas{border:1px solid;}
<canvas id="chart"></canvas>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.