因此,我正在尝试创建一个动画图表,该图表中的一个栏从下到上都是动画的。问题是当我运行它时,仅显示一个没有动画的栏。 有人可以帮忙吗?
代码:
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;
}
答案 0 :(得分:2)
由于您没有给我sort
的结果,所以我发明了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;}