Skip to content

Instantly share code, notes, and snippets.

@itzaks
Created April 23, 2014 15:55
Show Gist options
  • Select an option

  • Save itzaks/11221058 to your computer and use it in GitHub Desktop.

Select an option

Save itzaks/11221058 to your computer and use it in GitHub Desktop.
Lightweight Pie Chart module
module.exports =
class Pie
pos: 0
colors: ['yellow', 'black']
constructor: (@canvas, {@yes, @no}) ->
@data = [@yes, @no]
@context = canvas.getContext("2d")
#uses underscore for reduce but just swap with vanilla js if needed
@total = _.reduce @data, (memo, num) -> memo + num
@draw()
draw: ->
center = x: @canvas.width / 2, y: @canvas.height / 2
pi = Math.PI
for value, i in @data
percentage = (value / @total)
@context.fillStyle = @colors[i]
@context.beginPath()
@context.moveTo center.x, center.y
@context.arc center.x, center.y, center.y, @pos, @pos + (pi * 2 * percentage), no
@context.lineTo center.x, center.y
@context.fill()
@pos += pi * 2 * percentage
@itzaks
Copy link
Author

itzaks commented Apr 23, 2014

Usage:

 new Pie(@$('#canvas')[0], {yes: 50, no: 50})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment