Skip to content

Instantly share code, notes, and snippets.

@josimard
Last active August 29, 2015 14:13
Show Gist options
  • Save josimard/947aa594aab3b229e1d0 to your computer and use it in GitHub Desktop.
Save josimard/947aa594aab3b229e1d0 to your computer and use it in GitHub Desktop.
Arc view
/**
* Arc View
* https://gist.github.com/josimard/947aa594aab3b229e1d0
*
* Inspired from http://jsfiddle.net/oskar/Aapn8/
*
* More cool stuff @ http://padolsey.net/p/Sonic/repo/demo/demo.html
*
* Example use:
*
var arcView = new ArcView({
element: $("#arc"),
progress:0.5,
color: #99CC33',
radius: 60,
lineWidth: 10,
anim: {
time:5
}
});
arcView.setProgress(1);
*
* dependencies:
* - jQuery
*
* @author jo@josimard.com
*/
function ArcView(settings)
{
// Default Options
this.settings = $.extend({
element:null,
id: "arcView_"+new Date().getTime(),
cssClass:"arcView",
radius: 60,
lineWidth: 10,
color: '#99CC33',
progress: 0,
anim: {
time: 1, // Time in SECONDS
easing: (jQuery.easing["easeOutQuint"]) ? "easeOutQuint" : null
}
}, settings);
this.element = $(this.settings.element);
this.progress = this.settings.progress;
this.canvas;
this.ctx;
this.circ = Math.PI * 2;
this.quart = Math.PI / 2;
this.init();
}
ArcView.prototype.init = function()
{
$('<canvas>').attr({
"id": this.settings.id,
"class": this.settings.cssClass,
"width": this.settings.radius,
"height": this.settings.radius
}).appendTo(this.element);
this.canvas = $(this.element).find("canvas")[0];
// Incompatible browser
if(!$.isFunction(this.canvas.getContext)) return;
var ctx = this.canvas.getContext('2d');
ctx.beginPath();
ctx.strokeStyle = this.settings.color;
ctx.lineCap = 'square';
ctx.closePath();
ctx.fill();
ctx.lineWidth = this.settings.lineWidth;
this.ctx = ctx;
if(this.progress>0)
{
this.drawArc(this.progress);
}
}
ArcView.prototype.drawArc = function(progress)
{
if(!this.ctx) return;
this.ctx.clearRect(0, 0, this.settings.radius, this.settings.radius);
this.ctx.beginPath();
this.ctx.arc(this.settings.radius*0.5, this.settings.radius*0.5, this.settings.radius*0.5-this.settings.lineWidth, -(this.quart), ((this.circ) * progress) - this.quart, false);
this.ctx.stroke();
}
ArcView.prototype.setProgress = function(to, time, easing)
{
if(!this.canvas) return;
if(!time) time = this.settings.anim.time;
if(!easing) easing = this.settings.anim.easing;
// Using jQuery.animate() for easing
var from = this.progress;
var context = this;
$(this.canvas).stop().animate({'fake-property': 1 }, {
duration: time*1000,
easing: easing,
step: function( value ) {
context.drawArc(from+(value*(to-from)));
}
});
this.progress = to;
}
ArcView.prototype.getProgress = function() {
return this.progress;
}
ArcView.prototype.element = function() {
return this.canvas;
}
return ArcView;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment