canvas环形抢购进度显示
查看演示
<div><canvas data-num="60" width="80" height="80" class="canvas"></canvas></div> <div><canvas data-num="80" width="80" height="80" class="canvas"></canvas></div> <div><canvas data-num="50" width="80" height="80" class="canvas"></canvas></div>
function arcCanvas(num,canvasEle){ var residual = num;//剩余量 var canvas = canvasEle, context = canvas.getContext('2d'),//获取画圆环境,指明为2d centerX = canvas.width/2,//圆的中心X点 centerY = canvas.height/2,//圆的中心Y点 rad = Math.PI *2 /100,//将圆分成100分,那么每份就是rad度 speed = 0.1; //外圈 function blueCircle(n){ context.save(); context.strokeStyle ="#ff8265";//描边样式 context.lineWidth = 5;//设置线宽 context.lineCap = "round"; context.beginPath();//路径开始 //用于绘制圆弧context.arc(x左边,y坐标) context.arc(centerX,centerY,30,-Math.PI/2,-Math.PI/2 +n*rad,false); context.stroke();//绘制 context.closePath();//路径结束 context.restore(); } //内圈 function whiteCircle(){ context.save(); context.strokeStyle='#ffefdf'; context.lineWidth=5; context.beginPath(); context.arc(centerX,centerY,30,0,Math.PI *2 ,false); context.stroke(); context.closePath(); context.restore() } //百分比文字绘制 function text(n){ context.save();//save 跟restore 可以保证样式属性只用于该段的canvas context.strokeStyle='#ff5933'; context.fillStyle="#ff5933"; context.font = '14px arial'; context.fillText("已抢",centerX-15,centerY-5); //绘制字体并且制定位置 context.strokeText(n.toFixed()+"%",centerX-15,centerY+10); //context.stroke(); context.restore(); } //初始化 (function drawFrame(){ window.requestAnimationFrame(drawFrame); context.clearRect(0, 0, canvas.width, canvas.height); whiteCircle(); blueCircle(speed); text(speed); //ajax if (speed < residual) { speed+=0.3; }else{ speed = residual; } }()); } $('.canvas').each(function(){ var num = parseInt($(this).attr('data-num')), canvasEle = $(this)[0]; arcCanvas(num,canvasEle); })