📖 技术要求: 有一点点数学的基础以及对canvas的基础掌握
话不多说直接上代码,开袋即食,你们觉得香不香呢 ❗️❗️❗️
function draw_circle_progress (num) {
let canvas = document.getElementById('canvasD'),
context = canvas.getContext('2d'), //获取画图环境,指明为2d
centerX = canvas.width / 2, //Canvas中心点x轴坐标
centerY = canvas.height / 2, //Canvas中心点y轴坐标
rad = (Math.PI * 2) / 100; //将360度分成100份,那么每一份就是rad度
//绘制5像素宽的运动外圈
function blueCircle(n) {
context.save();
context.strokeStyle = '#587CF3'; //设置描边样式
context.lineWidth = 5; //设置线宽
context.beginPath(); //路径开始
context.arc(
centerX,
centerY,
centerX - 5,
-Math.PI / 2,
-Math.PI / 2 + n * rad,
false
); //用于绘制圆弧context.arc(x坐标,y坐标,半径,起始角度,终止角度,顺时针/逆时针)
context.stroke(); //绘制
context.closePath(); //路径结束
context.restore();
}
//绘制白色外圈
function whiteCircle() {
context.save();
context.beginPath();
context.lineWidth = 4; //设置线宽
context.strokeStyle = '#fff';
context.arc(centerX, centerY, centerX - 5, 0, Math.PI * 2, false);
context.stroke();
context.closePath();
context.restore();
}
// 获取字符串的宽度
function getTextWidth(str) {
let width = 0;
let html = document.createElement('span');
html.innerText = str;
html.className = 'getTextWidth';
document.querySelector('body').appendChild(html);
width = document.querySelector('.getTextWidth').offsetWidth;
document.querySelector('.getTextWidth').remove();
return width;
}
//动画循环
(function drawFrame() {
let fontStyle = 'normal bold 24px Arial,sans-serif'
let text = `${num}%`
let center_x_num = getTextWidth(text) / 2
context.clearRect(0, 0, canvas.width, canvas.height);
context.font = fontStyle; //设置字体大小和字体
context.fillStyle = '#fff';
// 此处的判断是为了调整百分比再圆环的位置, 区分出来 xx% 和 xxx%,达到一个居中的效果
if (num < 10) context.fillText(num + '%', centerX - center_x_num, centerY);
else context.fillText(num + '%', centerX - center_x_num, centerY);
}
whiteCircle();
blueCircle(text);
})();
return canvas.toDataURL(); // 由于需求我需要base64所以调用次方法
};