JS實現圓形進度條拖拽滑動
本文實例為大傢分享瞭JS實現圓形進度條拖拽滑動的具體代碼,供大傢參考,具體內容如下
效果展示
半圓進度條效果
圓形進度條
代碼實現
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <title> 圓形進度條拖拽滑動 </title> </head> <body> <canvas id="canvasId" width="400" height="400"></canvas> <script type="text/javascript"> var canvas = document.getElementById("canvasId"); var ctx = canvas.getContext("2d"); var ox = 200; var oy = 200; var or = 180; var br = 15; var moveFlag = false; function offset(r,d) {//根據弧度與距離計算偏移坐標 return {x: -Math.sin(r)*d, y: Math.cos(r)*d}; }; function draw(n) { ctx.clearRect(0,0,canvas.width,canvas.height); ctx.strokeStyle = "#99a"; ctx.lineWidth = 5; ctx.beginPath(); ctx.arc(ox,oy,or,0,Math.PI,true);//半圓 // ctx.arc(ox,oy,or,0,2*Math.PI,true);//整圓 ctx.stroke(); ctx.strokeStyle = "#69f"; ctx.lineWidth = 5; ctx.beginPath(); ctx.arc(ox,oy,or,Math.PI,(n*2+0.5)*Math.PI,false); // ctx.arc(ox,oy,or,0.5*Math.PI,(n*2+0.5)*Math.PI,false); ctx.stroke(); ctx.fillStyle = "#69f"; ctx.font = "80px Arial"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillText(Math.round(n*100-25)+"%",ox,oy); ctx.fillStyle = "#00f"; ctx.beginPath(); var d = offset(n*2*Math.PI,or); ctx.arc(ox+d.x,oy+d.y,br,0,2*Math.PI,true); ctx.fill(); } var on = ("ontouchstart" in document)? { start: "touchstart", move: "touchmove", end: "touchend" } : { start: "mousedown", move: "mousemove", end: "mouseup" }; function getXY(e,obj) { var et = e.touches? e.touches[0] : e; var x = et.clientX; var y = et.clientY; return { x : x - obj.offsetLeft + (document.body.scrollLeft || document.documentElement.scrollLeft), y : y - obj.offsetTop + (document.body.scrollTop || document.documentElement.scrollTop) } } canvas.addEventListener(on.start, function(e) { moveFlag = true; }, false); canvas.addEventListener(on.move, function(e) { if (moveFlag) { var k = getXY(e,canvas); var r = Math.atan2(k.x-ox, oy-k.y); var hd = (Math.PI+r)/(2*Math.PI); // 半圓的滑動范圍判斷 if (hd <= 0.75 && hd >= 0.25) { draw(hd); } } }, false); canvas.addEventListener(on.end, function(e) { moveFlag = false; }, false); draw(0.25); </script> </body> </html>
以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。
推薦閱讀:
- JavaScript中html畫佈的使用與頁面存儲技術詳解
- javascript canvas實現雨滴效果
- 使用js實現動態背景
- JS canvas實現畫板和簽字板功能
- JS+Canvas繪制抽獎轉盤