執行個體講解canvas實現圓形進度條動畫

來源:互聯網
上載者:User
這篇文章主要介紹了canvas實現圓形進度條動畫的相關資料,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

本文介紹了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);
相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.