Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the movable canvas Ring Progress Bar by JavaScript

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of "how to realize the movable canvas ring progress bar in JavaScript". The editor shows you the operation process through the actual case, the operation method is simple and fast, and the practicality is strong. I hope this article "how to achieve the movable canvas ring progress bar in JavaScript" can help you solve the problem.

Introduction

Share the writing of a circular progress bar today, of course, this is just a movable static progress bar, you can add background data if you like. This kind of progress bar is very simple to write everywhere, but more of it is just a look, we can move this.

The premise is that you know the properties, methods and some basic js API of canvas, and of course, to make sure that some forgotten friends remember, I will make a list in front of it.

Property and method description getContext () returns an environment for drawing on canvas strokeStyle brush (drawing graphics) properties of color or style lineWidth properties of segment thickness save () methods to save the full state of canvas (stack) beginPath () methods to create a new path arc (origin x, origin y, radius, start angle, end angle Default false clockwise) methods to draw arc paths stroke () draw paths closePath () close draw paths restore () return to the nearest saved state (out of stack) attributes of fillStyle color and style font properties of the current font style toFixed (num) rounds Number to a specified number of decimal places

After reviewing the above table, I began to draw the graph. Besides the canvas element, the drawing of the graph has the following parts. First, I will write out the code separately.

1. Create a canvas element

First create a canvas label to give the width and height, draw the ring progress width and height can be the same, then get the element and create the canvas. Notice that the canvas element is named mycanvas here, and the canvas object drawn is called ctx.

/ / the following is js code var mycanvas = document.getElementById ('mycanvas'); var ctx = mycanvas.getContext (' 2d'); 2. Preparation for drawing

Some preparatory work needs to be done before drawing.

To find the "center of the canvas", the progress bar

Divide the progress bar into 100 parts according to the proportion of progress and complete it according to 100%.

Specify the initial loading step (length). Note that it can be changed to 0 in the later stage of initialization.

/ / to find the center point of the canvas var canvasX = mycanvas.width / 2 position var canvasY = mycanvas.height / 2 position bank / progress bar is 100%, so divide a circle of 360 degrees into 100 parts var progress = Math.PI * 2 / 100 X X / specify the initial loading step var steps = 0.5%. Draw the bottom layer of the ring

First draw the light gray ring at the bottom of the progress ring, which is the path of the progress. You can first specify the color and lineweight of the drawing, which have no effect on the order of the following methods.

Ctx.strokeStyle ='# dddddd';ctx.lineWidth = 20 ctx.closePath. Save (); ctx.beginPath (); ctx.arc (canvasX, canvasY, 90,0, Math.PI * 2, false) ctx.stroke (); ctx.closePath (); ctx.restore (); 4. Draw the progress layer

The color of the progress layer needs to be defined, and the thickness of the progress bar is the same as that of the underlying ring. The most important sentence here is that the "steps progress" step progress is added at the end of the angle. The smaller the steps number is, the less the angle increases after the multiplier, and the more the progress increases after the large multiplier of the steps number.

Ctx.strokeStyle = "# 47cab0"; ctx.lineWidth = 20 scape ctx.save (); ctx.beginPath (); ctx.arc (canvasX,canvasY,90,-Math.PI/2,-Math.PI/2+steps*progress,false); ctx.stroke (); ctx.closePath (); ctx.restore (); 5. Draw the font and specify the location

The circular percentage of progress text shows that you need to use canvas text to draw, here you need to note that the number is from 1 to 3 digits span, but also add%, so the position needs to change. When the number reaches 100, the text occupies a larger width, so change the starting point of the drawing.

Ctx.fillStyle = "# 000000"; / / modifiable ctx.font = "bold 26px Arial"; / / modifiable ctx.save (); / / canvasX-30, the value of addition and subtraction in canvasY+10 can be changed to if (steps.toFixed (0). Length = = 3) {ctx.fillText (steps.toFixed (0) +'%', canvasX-30, canvasY+10);} else {ctx.fillText (steps.toFixed (0) +'%', canvasX- 20, canvasY+10);} ctx.restore ()

At this point, a static progress will appear, but we still need to get it moving, the timer that you might think of. But we used another way to write circular animation.

6. Progress animation

The refresh rate of the monitor is usually 50MHz 60hz, 1000ms hand, 60 ≈ 16.6ms, which is equivalent to redrawing 60 times per second, and most browsers do not exceed the redrawing frequency of the monitor. As we mentioned in previous articles, setTimeout () and setInterval () loops are not exactly smart, and even if you use setTimeout () to simulate loop timers in a self-tuning manner, there is no guarantee that the processing thread will behave as desired.

Window.requestAnimationFrame ()

Window.requestAnimationFrame () tells the browser that you want to perform an animation and asks the browser to call the specified callback function to update the animation before the next redraw. This method needs to pass in a callback function as an argument, which will be executed before the browser's next redraw. The callback function is usually executed 60 times per second, but in most browsers that follow W3C recommendations, the callback function execution times usually match the number of browser screen refreshes. In order to improve performance and battery life, in most browsers, when requestAnimationFrame () is running in the background tab or hidden, requestAnimationFrame () is paused to improve performance and battery life.

So to ensure smooth rendering, we use window.requestAnimationFrame () to do a few things in a callback function of the method's parameters:

1. It is judged that the end value of completing the whole ring step, such as 100, is actually walking to 100%, and 75 is going to 75%.

two。 Call the growing function within the selected step size

Window.requestAnimationFrame (function () {/ / the boundary value to determine how far the step will eventually go, which can be changed to if (steps < 90) {/ / this function can call the function within the boundary, increase the step size and draw a graph to give the function a name}})

Because of the self-calling of the function, we write this part together without splitting it. That's where the difficulty lies!

Step 1: to do this first, put all the previous drawing code into the newly created function DrawShape, and you need to receive two parameters. One is the object to be drawn, because there is more than one canvas object on a page. The second parameter is the step size that changes each time.

/ / draw the shape function, pass in the canvas object and the step size function DrawShape (ctx,steps) {/ / draw a circle to draw the underlying circle. / / draw the progress circle to draw the progress bar. / / the code to draw the font and specify the location to draw the font.}

Step 2: create an animate function to perform three important things: smooth animation, increase in step size, and draw graphics.

/ / the animation function animate () is initially called; / / the animation function function animate () {/ / executes the boundary value of smooth animation window.requestAnimationFrame (function () {/ /) to determine how far the step will go, which can be changed to if (steps < 90) {/ / the function can call animate ();}}); / / clear the drawing content ctx.clearRect (0, 0, mycanvas.width, mycanvas.height) / / with each increase in step size, the larger the number, the bigger the step, the faster the run, the smaller the number, the slower the step. The smaller the number is, the slower the step is. Steps + = 0.5 control / change / / call the drawing shape function, pass in the parameter drawing object, the ring progress step DrawShape (ctx,steps);}; this is the end of the content on "how JavaScript implements the movable canvas ring progress bar". Thank you for your reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report