html5 canvas半圆环百分比进度条动画特效
<!DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <title>动态画一半圆环</title> </head> <body> <div class="ring" style="text-align: center;"> <canvas id="tutorial" width="125" height="125"></canvas> <div class="fraction"><span class="numberOne">95</span></div> <span class="title">半圆环</span> </div> <script> let radius = 60; //外环半径 let thickness = 10; //圆环厚度 let innerRadius = radius - thickness; //内环半径 let startAngle = -90; //开始角度 let endAngle = 180; //结束角度 let x = 0; //圆心x坐标 let y = 0; //圆心y坐标 let canvas = document.getElementById("tutorial"); canvas.width = 125; canvas.height = 125; let ctx = canvas.getContext("2d"); ctx.translate(canvas.width / 2, canvas.height / 2); //将绘图原点移到画布中央 ctx.rotate(angle2Radian(225)); //将画布旋转225度 ctx.fillStyle = "#eee"; //初始填充颜色 renderRing(startAngle, endAngle); //渲染函数 function renderRing(startAngle, endAngle) { ctx.beginPath(); //绘制外环 ctx.arc(x, y, radius, angle2Radian(startAngle), angle2Radian(endAngle)); //计算外环与内环第一个连接处的中心坐标 let oneCtrlPoint = calcRingPoint( x, y, innerRadius + thickness / 2, endAngle ); //绘制外环与内环第一个连接处的圆环 ctx.arc( oneCtrlPoint.x, oneCtrlPoint.y, thickness / 2, angle2Radian(-90), angle2Radian(270) ); // //绘制内环 ctx.arc( x, y, innerRadius, angle2Radian(endAngle), angle2Radian(startAngle), true ); //计算外环与内环第二个连接处的中心坐标 let twoCtrlPoint = calcRingPoint( x, y, innerRadius + thickness / 2, startAngle ); //绘制外环与内环第二个连接处的圆环 ctx.arc( twoCtrlPoint.x, twoCtrlPoint.y, thickness / 2, angle2Radian(-90), angle2Radian(270) ); ctx.fill(); // ctx.stroke() } //计算圆环上点的坐标 function calcRingPoint(x, y, radius, angle) { let res = {}; res.x = x + radius * Math.cos((angle * Math.PI) / 180); res.y = y + radius * Math.sin((angle * Math.PI) / 180); return res; } //弧度转角度 function radian2Angle(radian) { return (180 * radian) / Math.PI; } //角度转弧度 function angle2Radian(angle) { return (angle * Math.PI) / 180; } //进度条颜色 var lingrad = ctx.createLinearGradient(0, 0, 150, 0); lingrad.addColorStop(0, "#00ABEB"); lingrad.addColorStop(1, "#fff"); ctx.fillStyle = lingrad; //开始绘画 let tempAngle = startAngle; let total = 1000; //总分 let now = 950; //当前分数 let percent = now / total; //百分比 let twoEndAngle = percent * 270 + startAngle; let step = (twoEndAngle - startAngle) / 80; let numberSpan = document.querySelector(".numberOne"); let inter = setInterval(() => { if (tempAngle > twoEndAngle) { clearInterval(inter); } else { numberSpan.innerText = percent * 100; tempAngle += step; } renderRing(startAngle, tempAngle); }, 20); </script> </body> </html>
vue中使用圆环可以直接使用element-ui组件库 elementui地址 :https://element.eleme.cn/#/zh-CN/component/progress