Created
November 24, 2012 10:29
-
-
Save tiraeth/4139118 to your computer and use it in GitHub Desktop.
Morris.Gauge
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Morris.Gauge extends Morris.EventEmitter | |
defaults: | |
stroke: "#f39d11" | |
strokeWidth: 28 | |
duration: 500 | |
easing: "<" | |
maxValue: 100 | |
initialValue: 0 | |
constructor: (options) -> | |
@el = $ options.element | |
if @el is null or @el.length == 0 | |
throw new Error("Container element not found") | |
@options = $.extend {}, @defaults, options | |
@r = Raphael @el.attr("id"), @el.width(), @el.height() | |
@cx = @el.width() / 2 | |
@cy = @el.height() / 2 | |
@radius = Math.min(@cx, @cy) - @options.strokeWidth | |
@value = @options.initialValue | |
@init() | |
init: -> | |
@addCustomAttributes() | |
@draw() | |
addCustomAttributes: -> | |
@r.customAttributes.arc = (cx, cy, radius, value, total) => | |
value = if value < 0 then 0 else Math.ceil(value) | |
total = total ? 100 | |
value = total if value > total | |
alpha = 360 / total * value | |
a = (90 - alpha) * Math.PI / 180 | |
x = if total == value then cx - 0.01 else cx + radius * Math.cos(a) | |
y = if total == value then cy - radius else cy - radius * Math.sin(a) | |
flag = if total == value then 1 else +(alpha > 180) | |
{ path: [["M", cx, cy - radius], ["A", radius, radius, 0, flag, 1, x, y]] } | |
changeValue: (value) -> | |
@fire("updating", @value, value) | |
@fire("update", @value, value) | |
clearInterval @interval | |
$(value: @value).animate({ value: value }, | |
duration: @options.duration | |
easing: "swing" | |
step: (now) => @fire("updating", now, value) | |
) | |
@chart.animate({ | |
"stroke": @getStroke value | |
"arc": [@cx, @cy, @radius, value, @options.maxValue] | |
}, @options.duration, @options.easing, () => | |
@fire("updating", @value, value) | |
@value = value | |
@fire("updated", @value) | |
) | |
getStroke: (value) -> | |
if typeof @options.stroke is 'function' | |
return @options.stroke.call @, value | |
@options.stroke | |
draw: -> | |
@el.html("") | |
@chart = @r.path().attr | |
"stroke": @getStroke @value | |
"stroke-width": @options.strokeWidth | |
"arc": [@cx, @cy, @radius, @value, @options.maxValue] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment