Class: SimpleCharts::Chart

Inherits:
Object
  • Object
show all
Defined in:
lib/simple_charts.rb

Instance Method Summary collapse

Instance Method Details

#create_doughnut_paths(data, opts) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/simple_charts.rb', line 6

def create_doughnut_paths(data, opts)
  total = data.inject(:+)
  segments = data.map{ |val| 360 * val / total }
  centroid = opts[:width] / 2
  svg_padding = 5
  centroid_padding = opts[:centroid_padding] || 0
  radius = centroid - svg_padding
  end_angle = 0
  paths = []

  segments.each do |segment|
    start_angle = end_angle
    end_angle = start_angle + segment

    outer_edge_start_x = (centroid + radius * Math.cos(Math::PI * start_angle / 180)).round.to_s
    outer_edge_start_y = (centroid + radius * Math.sin(Math::PI * start_angle / 180)).round.to_s
    outer_edge_end_x = (centroid + radius * Math.cos(Math::PI * end_angle / 180)).round.to_s
    outer_edge_end_y = (centroid + radius * Math.sin(Math::PI * end_angle / 180)).round.to_s
    inner_edge_end_x = (centroid + centroid_padding * Math.cos(Math::PI * end_angle / 180)).round.to_s
    inner_edge_end_y = (centroid + centroid_padding * Math.sin(Math::PI * end_angle / 180)).round.to_s
    inner_edge_start_x = (centroid + centroid_padding * Math.cos(Math::PI * start_angle / 180)).round.to_s
    inner_edge_start_y = (centroid + centroid_padding * Math.sin(Math::PI * start_angle / 180)).round.to_s

    # move to start of outer arc
    path = 'M' + outer_edge_start_x + ',' + outer_edge_start_y

    # arc to outer edge of segment
    path += ' A ' + radius.to_s + ',' + radius.to_s + ' 0 ' + ((end_angle - start_angle > 180) ? '1' : '0') + ' 1 ' + outer_edge_end_x + ',' + outer_edge_end_y

    # line to inner edge of segment
    path += ' L ' + inner_edge_end_x + ',' + inner_edge_end_y

    # arc to inner other edge of segment
    path += ' A ' + centroid_padding.to_s + ',' + centroid_padding.to_s + ' 0 ' + ((end_angle - start_angle > 180) ? '1' : '0') + ' 0 ' + inner_edge_start_x + ',' + inner_edge_start_y + ' z'

    paths << path
  end

  paths
end

#render(type, data, opts) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/simple_charts.rb', line 47

def render(type, data, opts)
  svg = "<svg width='#{opts[:width]}' height='#{opts[:height]}' id='#{opts[:id]}' xmlns='http://www.w3.org/2000/svg'>"

  if type == 'pie' || type == 'doughnut'
    create_doughnut_paths(data, opts).each_with_index do |path, index|
      svg += "<path d='#{path}' id='#{opts[:id]}-path-#{index}'></path>"
    end
  end

  svg + '</svg>'
end