canvas 中的动画栏

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,因为它效率更高。如果您愿意,可以改用 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>