Canvas sample code for circular progress bar Animation
This article introduces canvas to achieve circular progress bar animation and shares it with you as follows:
Let's take a look at the code first.
Progress bar Animation
1. the HTML part of canvas is a canvas label.
The width and height of the canvas are attributes of the canvas. You need to set the style between lines. Setting the width and height of the canvas will make the picture distorted.
<canvas id="mycanvas" width="100" height="100">70%</canvas>
2. js code of the canvas
Main Idea: the middle is composed of three circles, and the outermost layer is a large circle with a black edge. inside it is a circle that changes the progress bar and a circle with a realistic percentage.
Note: You must create a new layer for each circle, so that you can set the style of each layer separately without affecting each other, just like a ps layer, A complete design draft is composed of many layers.
Var canvas = document. getElementById ("mycanvas"); var context = canvas. getContext ("2d"); function draw (I) {// context of the large circle. beginPath (); context. lineWidth = 1; context. arc (50,50, 46,0, Math. PI * 2); context. strokeStyle = "gray"; context. stroke (); // large circle 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 (); // small circle context. beginPath (); context. arc (50,50, 30,0, Math. PI * 2); context. lineWidth = 1; context. strokeStyle = "gray"; 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. Use a timer to refresh the canvas to display the progress bar.
Use the context. clearRect () method to clear
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);
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.