HTML5 animation (2): Canvas implements a circular progress bar and displays the percentage of digits,
Effect
1. First Create html code
<canvas id="canvas" width="500" height="500" style="background:#000;"></canvas>
2. Create a canvas Environment
Var canvas = document. getElementById ('canvas '), // obtain the canvas Element context = canvas. getContext ('2d '), // obtain the drawing environment, specifying it as 2d centerX = canvas. width/2, // X axis coordinate of the Canvas center centerY = canvas. height/2, // the Y axis coordinate rad = Math of the Canvas center. PI * 2/100, // divide 360 degrees into 100 portions, so each portion is rad degree speed = 0.1; // The speed of loading depends on it
3. Draw a 5 pixel wide moving Outer Ring
// Draw the motion outer ring function blueCircle (n) {context. save (); context. strokeStyle = "# fff"; // sets the stroke style context. lineWidth = 5; // set the lineWidth context. beginPath (); // The path starts context. arc (centerX, centerY, 100,-Math. PI/2,-Math. PI/2 + n * rad, false); // used to draw an arc context. arc (x, y, radius, start angle, end angle, clockwise/counterclockwise) context. stroke (); // draw context. closePath (); // The path ends context. restore ();}
4. Draw the white outer ring
// Draw the white outer ring function whiteCircle () {context. save (); context. beginPath (); context. lineWidth = 2; // set the lineWidth context. strokeStyle = "red"; context. arc (centerX, centerY, 100, 0, Math. PI * 2, false); context. stroke (); context. closePath (); context. restore ();}
5. Percentage text rendering
Function text (n) {context. save (); // save and restore ensure that style attributes are only applied to the canvas element context. strokeStyle = "# fff"; // sets the stroke style context. font = "40px Arial"; // set the font size and font // draw the font and specify the position context. strokeText (n. toFixed (0) + "%", centerX-25, centerY + 10); context. stroke (); // execute the rendering context. restore ();}
6. Let it move
// Animation loop (function drawFrame () {window. requestAnimationFrame (drawFrame); context. clearRect (0, 0, canvas. width, canvas. height); whiteCircle (); text (speed); blueCircle (speed); if (speed> 100) speed = 0; speed ++ = 0.1 ;}());
Complete code
<! DOCTYPE html>