canvas实现圆环加载效果_html


整个效果分为三个部分:中间的百分比、环形进度条、细线圆环。

获取上下文环境:

            var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var conterX = canvas.width / 2;
var conterY = canvas.height / 2;
var rad = Math.PI * 2 / 100;
var speed = 0.1;

百分比:

            function text(n) {
context.save();
context.strokeStyle = "#49f";
context.font = "20px Arial";
context.strokeText(n.toFixed(0) + "%", conterX - 25, conterY + 10);
context.stroke();
context.restore();
}

环形进度条

            function blueCricle(n) {
context.save();
context.beginPath();
context.strokeStyle = "#49f";
context.lineWidth = 8;
context.arc(conterX, conterY, 100, -Math.PI / 2, -Math.PI / 2 + n * rad, false);
context.stroke();
context.closePath();
context.restore()
}

细线圆环

            function widthCricle() {
context.save();
context.beginPath();
context.strokeStyle = "red";
context.lineWidth = 4;
context.arc(conterX, conterY, 100, 0, Math.PI * 2, false);
context.stroke();
context.closePath();
context.restore();
}

进度效果:

            (function draw() {
window.requestAnimationFrame(draw, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);

widthCricle();
text(speed);
blueCricle(speed);

if (speed > 100) {
speed = 0;
}
speed += 0.1;
}())

整体代码:

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Canvas实现圆环加载效果</title>
<style lang="">
#canvas {
background: #000000
}
</style>
</head>

<body>
<canvas id="canvas" width="600" height="600"></canvas>
<script>
window.onload = function() {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var conterX = canvas.width / 2;
var conterY = canvas.height / 2;
var rad = Math.PI * 2 / 100;
var speed = 0.1;

function text(n) {
context.save();
context.strokeStyle = "#49f";
context.font = "20px Arial";
context.strokeText(n.toFixed(0) + "%", conterX - 25, conterY + 10);
context.stroke();
context.restore();
}

function blueCricle(n) {
context.save();
context.beginPath();
context.strokeStyle = "#49f";
context.lineWidth = 8;
context.arc(conterX, conterY, 100, -Math.PI / 2, -Math.PI / 2 + n * rad, false);
context.stroke();
context.closePath();
context.restore()
}

function widthCricle() {
context.save();
context.beginPath();
context.strokeStyle = "red";
context.arc(conterX, conterY, 100, 0, Math.PI * 2, false);
context.stroke();
context.closePath();
context.restore();
}

function draw() {
window.requestAnimationFrame(draw, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);

widthCricle();
text(speed);
blueCricle(speed);

if (speed > 100) {
speed = 0;
}
speed += 0.1;
}
draw();
}
</script>
</body>

</html>