【代码】使用Canvas绘制出圆形进度条

2023-03-15 09:32:31  阅读 1792 次 评论 0 条

主要的实现步骤:

1、绘制圆环

2、绘制进度环

3、绘制文字


直接上代码:

  function drawRound(param) {
				if (!param.temp) {
					param.temp = {
						currentValue: 0
					};
				}
				var canvas = param.canvas;


				if (!param.position_x) {
					param.position_x = canvas.width / 2;
				}
				if (!param.position_y) {
					param.position_y = canvas.height / 2;
				}

				var ctx = canvas.getContext('2d');
				ctx.clearRect(0, 0, canvas.width, canvas.height);
				//console.log(ctx);

				//画出底层圆形
				ctx.beginPath();
				ctx.arc(param.position_x, param.position_y, param.radius, 0, 2 * Math.PI, false);
				ctx.lineWidth = param.lineWidth;
				ctx.strokeStyle = param.unactiveColor;
				ctx.stroke();



				//画出进度
				var startAngle = 3 / 2 * Math.PI; //开始位置弧度,这样做是,默认从3点钟方向开始
				var diffAngle = (param.temp.currentValue / 10) * Math.PI * 2; //结束角的弧度值(完成进度弧度值),前面那个除法就是在这个100*的圆形中占比多少
				ctx.beginPath();
				ctx.arc(param.position_x, param.position_y, param.radius, startAngle, startAngle + diffAngle,
					false); //起始弧度+结束弧度就是要画上去的
				ctx.strokeStyle = param.activeColor;
				ctx.stroke();


				//画出数值
				ctx.fillStyle = param.textColor;
				ctx.textAlign = 'center';
				ctx.font = param.textSize + 'px ' + (param.font_family ? param.font_family : "serif");
				ctx.fillText(param.text, param.position_x, param.position_y + (param.textSize / 2));

				
				//动画
				param.temp.currentValue = param.temp.currentValue + 0.1;
				if (param.temp.currentValue > param.val) {
					param.temp.currentValue = param.val;
				} else {
					window.requestAnimationFrame(function() {
						drawRound(param);
					});
				}

			}

参数:

var param = {
                canvas: c,//canvas对象,需要是JavaScript对象,不能是JQuery对象
                //position_x: 20,//位置x,不填写的话默认是正中间
                //position_y:20,//位置y,不填写的话默认是正中间
                val: 3.5,//数值,最好是百分比,取值范围1-10
                unactiveColor: "#9e9e9e",//进度环的底色,也就是未被覆盖到的
                activeColor: "rgb(0,162,232)",//进度环填充后的颜色
                lineWidth: 5,//进度环的厚度
                radius:16,//半径
                text: "35%",//中间显示的文本
                textColor: "#666",//字体颜色
                textSize: 10,//字体大小
                font_family: "MicrosoftYaHei"//字体名称
                

};

实现效果:

image.png


微信扫码查看本文
本文地址:https://www.yangguangdream.com/?id=2229
版权声明:本文为原创文章,版权归 编辑君 所有,欢迎分享本文,转载请保留出处!

发表评论


表情

还没有留言,还不快点抢沙发?