本文介紹了canvas實作圓形進度條動畫,分享給大家,具體如下:
先給大家看看效果圖,然後在上程式碼。
進度條動畫
1. canvas的HTML部分很簡單就一個canvas標籤canvas畫布的寬高是自身的屬性,要在行間樣式設置,若是在style設定寬高會使你畫的圖片變形。
<canvas id=mycanvas width=100 height=100>70%</canvas>2.畫布的js程式碼
主要想法:效果圖中是由三個圓組成的,最外層是一個有黑邊的大圓,裡面一個改變進度條進度的圓和一個現實百分比的圓。
注意:每畫一個圓都要新建一個圖層,這樣可以單獨設定每個圖層的樣式,之間不互相影響,就像ps的圖層一樣,一個完整的設計稿都是很多圖層組成的。
var canvas = document.getElementById(mycanvas);var context = canvas.getContext(2d);function draw(i){// 大圓框context.beginPath();context.lineWidth = 1;context.arc(50,50, 46,0,Math.PI*2);context.strokeStyle = grey;context.stroke();// 大圓context.beginPath();var grd = context.createLinearGradient(15,15,80,80);grd.addColorStop(0,red);grd.addColorStop(0.5,yellow);grd.addColorStop(1,blue);context.arc(50,50,38, 0,Math.PI*2*(i/100));context.lineWidth = 16;context.strokeStyle = grd;context.stroke();// context.fillStyle = grd;// context.fill();// 小圓context.beginPath();context.arc(50,50,30, 0,Math.PI*2);context.lineWidth = 1;context.strokeStyle = grey;context.stroke();context.fillStyle = white;context.fill();// 字context.beginPath();context.textBaseline = middle;context.textAlign = center;context.font = 20px Arial;context. fillStyle = black;context.fillText(i+%,50,50);}3. 使用計時器來刷新畫布,達到進度條的效果
使用context.clearRect()方法來清空畫布的
var i = 0;var progress = parseInt(canvas.innerHTML);// console.log(progress);var timer = setInterval(function(){if(i >= progress){clearInterval(timer);}context.clearRect (0,0,canvas.width,canvas.height);draw(i);i++;},50);
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。