本案例主要用到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>
代码量总体来讲不多,要写出可维护行好,复用性高的代码还得平时多写~~~