Canvas implements a circular progress bar

The effect

code

    var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext("2d"); / * * * @ author xie xiu make * @ licence MIT * / / * * * * @ description https://juejin.cn/post/6844904056658329613 draw circular progress bar * @param {number} angle * @param {number} x * @param {number} y * @param {number} radius * @param {Object} option */ var drawRoundProgress = (ctx, angle, x, y, radius, Option) => {/** * drawCircle * @param {Object} o */ var drawCircle = (o) => {var CTX = o.ctx.beginPath (); Ctx. lineWidth = O.line. width ctx.arc(O.x, O.y, O.adius, 1.5 * math. PI, (1.5 + (O.angle * 2)) * math. PI,false);
              ctx.lineCap = 'round'; ctx.strokeStyle = o.color ctx.stroke(); ctx.closePath(); } drawCircle({ ctx, angle: 1, color: option.layerColor, lineWidth: 3, x: x + radius, y: y + radius, radius, }) drawCircle({ ctx, angle, color: option.fill, lineWidth: 6, x: x + radius, y: RoundY + rem(101), roundX + REM (608), rem(162) / 2, { layerColor:'#1F67A5',
            fill: '#FFDF00',})Copy the code

Code parsing

The core is the ctx.arc function

CTX. Arc (o.x, o.y o.r adius, 1.5 * math.h PI, (1.5 + (o.a ngle * 2)) * Math in PI,false);
Copy the code

The first two are the central coordinates which are x and y and the third is the radius and the third and the fourth is the Angle at which you start and end and the last is whether it’s clockwise or not

The wheel test

With that in mind, let’s try it out.

var drawCircle = (o) => { ctx.beginPath(); Arc (o.x, O.Y, O.adius, 0, math.pi * 0.5,false); ctx.strokeStyle = o.color ctx.stroke(); ctx.closePath(); } drawCircle({Angle: 0.1, color:'#FFDF00',
		lineWidth: 6,
		x: 50,
		y: 50,
		radius: 30,
	})
Copy the code

The results

?????

What’s wrong? Where’s the rounded corner? Where’s the starting point to the right.

Rounded corners

Since the core function does not have rounded corners, it is set elsewhere.

You can find it if you’re looking for a girlfriend

ctx.lineCap = 'round';
Copy the code

This line of code, when you add it, you have rounded corners.

But the starting point is not quite right. The renderings start at the top.

Angle problem

At this point we need to look at the following map

Starting Angle

You can see that. 0 is on the right and 1.5 is the start, so we set the start to 1.5 * math.pi

With a beginning, we need an end

End Angle setting

Because it starts at 1.5. We need to set the offset to 1.5, but now we see that the circle is 2, which is hard to calculate, so we need to change it to 1, so we can pass in the percentage later, so we say (1.5 + (Angle * 2)) * math.pi

Now what Angle is, we’ll display it correctly

So the code

Try it again

CTX. Arc (o.x, o.y o.r adius, 1.5 * math.h PI, (1.5 + (o.a ngle * 2)) * Math in PI,false);
Copy the code

Ok, perfect.

– the –