[英]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.