canvas+js實現進度條
阿新 • • 發佈:2019-02-04
本案例主要用到canvas的一些基本的畫布操作,難度不是很大,主要是要熟悉js中的模組模式的寫法,學會面向物件的寫法對程式碼的維護和可讀性都有很大好處.
效果圖:
html程式碼:
<div id="cycle1"></div>
js程式碼:
<script type="text/javascript"> window.onload = function(){ //圓環物件 function Cycle(opts){ this.id = opts.id; this.width = opts.width; this.border = opts.border; this.height = opts.height; this.bgcolor= opts.bgcolor; this.pcolor = opts.pcolor; this.textcolor = opts.textcolor; this.percent = opts.percent; }; //動態擴充套件內建方法 Cycle.prototype = { constructor:Cycle,//宣告指向構造器 init:function(){ //建立畫布物件 var html = "<canvas id='canvas_"+this.id+"' width='"+this.width+"' height='"+this.height+"'></canvas>"; document.getElementById(this.id).innerHTML = html; //初始化事件和引數 this.setOptions(); }, //設定引數 setOptions:function(){ //獲取畫布物件 var canvas = document.getElementById("canvas_"+this.id); //獲取畫布的上下文 var context = canvas.getContext("2d"); var w = this.width; var h = this.height; var deg = this.percent; var cradius = w/2 - this.border; //清除畫布 context.clearRect(0,0,w,h); //開始繪畫 context.beginPath(); //設定圓的邊框 context.lineWidth = this.border; //繪製邊框的顏色 context.strokeStyle = this.bgcolor;//實心用fillstyle對應的方法是fill() //繪製圓 context.arc(w/2,h/2,cradius,0,2*Math.PI); //繪製到畫板中 context.stroke(); //計算一個角度對應弧度是多少 var d = deg*3.6/180*Math.PI; //重新繪製 context.beginPath(); //設定圓的邊框 context.lineWidth = this.border; //繪製邊框的顏色 context.strokeStyle = this.pcolor; //繪製圓 context.arc(w/2,h/2,cradius,-Math.PI/2,d-Math.PI/2); //繪製到畫板中 context.stroke(); //文字 context.beginPath(); //字型顏色 context.fillStyle=this.textcolor; //字型樣式 context.font = "28px 微軟雅黑" var text = deg+"%"; //獲取文字寬度 var textWidth = context.measureText(text).width; //繪製文字fillText("百分比",x,y); context.fillText(text,w/2-textWidth/2,h/2+14); } }; new Cycle({ id:"cycle1", width:300, height:300, border:30, percent:30, bgcolor:"gray", pcolor:"pink", textcolor:"#111" }).init(); }; </script>
程式碼量總體來講不多,要寫出可維護行好,複用性高的程式碼還得平時多寫~~~