JS canvas绘制进度条
在前端开发中,我比较喜欢Cavans画布,通过Cavans可以绘制自己想要的东西,在早之前,我通过Canvas播放视频,绘制图片,绘制banner图等,复杂点可以用来做数据的防盗窃等,譬如文章预览等,今天分析两个简单的实例,绘制圆形进度条和条形进度条
(一)绘制圆形进度条
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
*{
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<div style="text-align: center;padding-top: 15px">
<canvas id="canvas"></canvas>
</div>
</body>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
canvas.width = 650;
canvas.height = 650;
var progress = 0;
var time = window.setInterval(function(){
progressRound(progress);
progress ++;
if(progress > 100){
progress = 0;
window.clearInterval(time);
}
}, 15);
//圆形进度条
function progressRound(num){
var progress = 0.02 * num - 0.5;
var width = canvas.width;
var height = canvas.height;
context.lineWidth = 20; //进度条宽度
context.clearRect(0, 0, width, height);
context.lineCap = "round"; //线两端为圆角
//绘制地圈
context.beginPath();
context.strokeStyle = "#E4E2E2";
context.arc(width / 2, height / 2, (width / 2) - 10, 0, 2*Math.PI);
context.stroke();
//绘制顶层圈
context.beginPath();
context.strokeStyle ="#3B84F9";
context.arc(width / 2, height / 2, (width / 2) - 10, -0.5*Math.PI, progress*Math.PI); //-0.5~1.5
context.stroke();
//进度
context.beginPath();
context.textAlign = "center";
context.font = "20px Arial";
context.fillStyle = "#3B7DF9";
context.fillText(num.toFixed(1)+"%", width / 2, height / 2);
context.stroke();
//文字提示
context.beginPath();
context.textAlign = "center";
context.fillStyle = "#3B7DF9";
context.font = "20px Arial";
context.fillText("完成进度", width / 2, (height / 2) + 24);
context.stroke();
}
</script>
</html>
(二)绘制条形进度条
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
*{
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<div style="text-align: center;padding-top: 15px">
<canvas id="canvas"></canvas>
</div>
</body>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
canvas.width = 650;
canvas.height = 30;
var progress = 0;
var time = window.setInterval(function(){
progressLine(progress);
progress ++;
if(progress > 100){
progress = 0;
window.clearInterval(time);
}
}, 15);
function progressLine(num){
var progress = (canvas.width / 100) * num;
var width = canvas.width;
var height = canvas.height;
context.clearRect(0, 0, width, height);
//绘制底层背景
context.beginPath();
context.fillStyle = "#E4E2E2";
context.fillRect(0, 0, width, height);
context.stroke();
//绘制顶层进度条
context.beginPath();
context.fillStyle = "#3B84F9";
context.fillRect(0, 0, progress, height);
context.stroke();
//进度值
context.beginPath();
context.fillStyle = "#FFFFFF";
if(progress > 50){
context.textAlign = "right";
}else{
context.textAlign = "left";
}
context.font = "20px Arial";
context.fillText(num.toFixed(1)+"%", progress, height / 2 + 7);
context.stroke();
}
</script>
</html>