前提:有時候在項目中會有用到進度條的情況,使用css3也可以實現(xiàn),但是對于性能不好的設(shè)備,或者網(wǎng)絡(luò)不好的情況下,卡頓現(xiàn)象非常明顯,避免出現(xiàn)不流暢的尷尬情況,所以記錄一下,使用canvas來實現(xiàn)的方法。
var canvas = document.getElementById('canvas'), //獲取canvas元素
context = canvas.getContext('2d'), //獲取畫圖環(huán)境,指明為2d
centerX = canvas.width / 2, //Canvas中心點x軸坐標
centerY = canvas.height / 2, //Canvas中心點y軸坐標
rad = Math.PI * 2 / 100, //將360度分成100份,那么每一份就是rad度
speed = 0.1; //加載的快慢就靠它了
//繪制藍色外圈
function blueCircle(n) {
context.save();
context.beginPath();
context.strokeStyle = "#49f";
context.lineWidth = 12;
context.arc(centerX, centerY, 100, -Math.PI / 2, -Math.PI / 2 + n * rad, false);
context.stroke();
context.restore();
}
//繪制白色外圈
function whiteCircle() {
context.save();
context.beginPath();
context.strokeStyle = "#A5DEF1";
context.lineWidth = 12;
context.arc(centerX, centerY, 100, 0, Math.PI * 2, false);
context.stroke();
context.closePath();
context.restore();
}
//百分比文字繪制
function text(n) {
context.save();
context.fillStyle = "#F47C7C";
context.font = "40px Arial";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(n.toFixed(0) + "%", centerX, centerY);
context.restore();
}
//動畫循環(huán)
(function drawFrame() {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
whiteCircle();
text(speed);
blueCircle(speed);
if (speed > 100) speed = 0;
speed += 0.1;
}());
window.requestAnimationFrame(drawFrame, canvas);