代码如下:
(function(w) {
function Cycle(options) {
this.id = options.id;
this.width = options.width;
this.height = options.height;
this.percent = options.percent;
this.border = options.border;
this.bgColor = options.bgColor;
this.barColor = options.barColor;
this.textColor = options.textColor;
};
Cycle.prototype = {
contructor: Cycle,
init: function() {
//创建画布对象
var html = "<canvas id='canvas_" + this.id + "' width='" + this.width + "' height='" + this.height + "'></canvas>";
document.getElementById(this.id).innerHTML = html;
var time = setInterval(function() {
this.percent++;
if(this.percent >= 100) {
clearInterval(time);
}
this.setOptions();
}.bind(this), 1000);
this.setOptions()
},
setOptions: function() {
var degree = this.percent;
var canvas = document.getElementById('canvas_' + this.id);
var context = canvas.getContext('2d');
context.clearRect(0, 0, this.width, this.height);
//开始绘画
context.beginPath();
context.lineWidth = this.border;
context.strokeStyle = this.bgColor;
context.arc(this.width / 2, this.height / 2, (this.width / 2 - this.border / 2), 0, 2 * Math.PI);
context.stroke();
var deg = degree * 3.6 / 180 * Math.PI
context.beginPath();
context.lineWidth = this.border;
context.strokeStyle = this.barColor;
context.arc(this.width / 2, this.height / 2, (this.width / 2 - this.border / 2), 0 - Math.PI / 2, deg - Math.PI / 2);
context.stroke();
context.beginPath();
context.fillStyle = this.textColor;
context.font = "18px 微软雅黑";
var text = degree + "%";
var textWidth = context.measureText(text).width;
context.fillText(text, this.width / 2 - textWidth / 2, this.height / 2 + 9);
}
}
w.Cycle=Cycle;
}(window))
效果如图:
使用说明:
var opts1 = {
id: "cycle1",
width: "300",
height: "300",
percent: "20",
border: "30",
bgColor: "green",
barColor: "yellow",
textColor: "pink"
};
var opts2 = {
id: "cycle2",
width: "400",
height: "400",
percent: "60",
border: "30",
bgColor: "gray",
barColor: "red",
textColor: "pink"
};
new Cycle(opts1).init();
new Cycle(opts2).init();
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。