<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Canvas制作动态进度加载水球</title>
<style type="text/css">
#c{
margin: 0 auto;
display: block;
}
#r{
display: block;
margin: 0 auto;
}
#r::before{
color: black;
content: attr(min);
padding-right: 10px;
}
#r::after{
color: black;
content: attr(max);
padding-left: 10px;
}
</style>
<script type="text/javascript">
window.onload=function() { var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
var range = document.getElementById('r'); //range控件信息
var rangeValue = range.value;// 默认5
var nowRange = 0; //用于做一个临时的range //画布属性
var mW = canvas.width = 250;
var mH = canvas.height = 250;
var lineWidth = 2; //圆属性
var r = mH / 2; //圆心
var cR = r - 16 * lineWidth; //圆半径 //Sin 曲线属性
var sX = 0;
var sY = mH / 2;
var axisLength = mW; //轴长
var waveWidth = 0.03 ; // 绝对值 波浪宽度,数越小越宽
var waveHeight = 6; //波浪高度,数越大越高
var speed = 0.10; //波浪速度,数越大速度越快 改变sin 的值
var xOffset = 0; //波浪x偏移量 ctx.lineWidth = lineWidth; //画圈函数
var IsdrawCircled = false;
var drawCircle = function(){ ctx.beginPath();
ctx.strokeStyle = '#1080d0';
ctx.arc(r, r, cR+5, 0, 2 * Math.PI);
ctx.stroke();
ctx.beginPath();
ctx.arc(r, r, cR, 0, 2 * Math.PI);
ctx.clip(); } //画sin 曲线函数
var drawSin = function(xOffset){ ctx.save(); var points=[]; //用于存放绘制Sin曲线的点 ctx.beginPath();
//在整个轴长上取点
// 250 20/250 ==3125 个点 绘制多个 x.y 点
for(var x = sX; x < axisLength; x += 20 / axisLength){
//此处坐标(x,y)的取点,依靠公式 “振幅高*sin(x*振幅宽 + 振幅偏移量)”
var y = -Math.sin(x * waveWidth + xOffset); // 返回-1 到 1 的值
var dY = mH * (1 - nowRange / 100 ); points.push([x, dY + y * waveHeight]);
ctx.lineTo(x, dY + y * waveHeight); }//--------------绘制波浪 //封闭路径 ctx.lineTo(axisLength, mH); //250 250 ---最右边
ctx.lineTo(sX, mH); //0 250 ----最左边 ctx.fillStyle = '#1c86d1';
ctx.fill(); ctx.restore();
}; //写百分比文本函数
var drawText = function(){
ctx.save(); var size = 0.4*cR;
ctx.font = size + 'px Microsoft Yahei';
ctx.textAlign = 'center';
ctx.fillStyle = "rgba(06, 85, 128, 0.8)";
ctx.fillText(nowRange + '%', r, r + size / 2); ctx.restore();
}; var render = function(){
ctx.clearRect(0, 0, mW, mH); rangeValue = range.value; if(IsdrawCircled == false){
drawCircle();
} if(nowRange <= rangeValue){
var tmp = 1;
nowRange += tmp;
} if(nowRange > rangeValue){
var tmp = 1;
nowRange -= tmp;
} if(rangeValue>0)
{
drawSin(xOffset);
}
drawText(); xOffset += speed; requestAnimationFrame(render);
}
render();
}
</script>
</head>
<body> </body>
<canvas id="c"></canvas>
<input type="range" id="r" min="0" max="100" step="1" value="0">
</html>
文章引用: Canvas制作动态进度加载水球
相关动画 : 基于canvas实现物理运动效果与动画效果(一)