SVG红宝石饼图 [英] SVG piechart with ruby

查看:70
本文介绍了SVG红宝石饼图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试生成一小段代码,这些代码将为我构造一个SVG饼图,如下所示:

I've tried to produce a small block of code which would construct for me a SVG piechart, listed below:

# piechart-svg.rb:
BEGIN {
  @colors = []
  both = %w(coral grey green salmon blue seagreen slategrey cyan)
  darks = %w(magenta red olivegreen orange turquoise goldenrod khaki orchid slateblue violet)
  lights = %w(steelblue yellow skyblue pink goldenrodyellow)
  @colors << both.map {|c| [c, "light#{c}", "dark#{c}"] }
  @colors << darks.map {|c| [c, "dark#{c}"] }
  @colors << lights.map {|c| [c, "light#{c}"] }
  @colors.flatten!

  @radius = 100.0
  @prevcoord = "#{@radius},0"
  puts <<-EOF
<?xml version="1.0" standalone="no" ?>
<svg xmlns="http://www.w3.org/2000/svg"
  preserveAspectRatio="xMinYMin"
  viewBox="-#{@radius},-#{@radius} #{@radius*2},#{@radius*2}">
  <defs>
    <style>
      .wedge { stroke: darkgrey; stroke-linejoin: round; fill-opacity: .2; }
    </style>
  </defs>
  EOF
}

ARGV.each_with_index do |percent,index|
  print "  <path class=\"wedge\" fill=\"#{@colors[index]}\" d=\""
  angle_as_degrees = percent.to_f / 100 * 360
  x = Math::cos(angle_as_degrees * 180 / Math::PI) * @radius
  y = Math::sin(angle_as_degrees * 180 / Math::PI) * @radius
  print "M#{@prevcoord} A#{@radius},#{@radius} 0 0,1 #{x},#{y} L0,0 Z\" />\n"
  @prevcoord = "#{x},#{y}"
end

END { puts "  <circle fill=\"none\" stroke=\"black\" r=\"#{@radius}\" />
</svg>" }

问题是,如果我进给它,例如说50%(ruby piechart-svg.rb 50),则产生的楔形小于圆的一半.我不明白为什么.

The trouble is, if I feed it, say, 50% (ruby piechart-svg.rb 50), the produced wedge is less than half of the circle. I don't understand why.

推荐答案

您可以将弧度的度数向后转换.应该是:

You have your degrees to radians conversion backwards. Should be:

x = Math::cos(angle_as_degrees * Math::PI / 180) * @radius
y = Math::sin(angle_as_degrees * Math::PI / 180) * @radius

请注意,如果任何切片大于50%,您仍然会遇到问题,但这与该问题是分开的. :)

Note that you still have problems if any slice is greater than 50%, but that's separate from this question. :)

这篇关于SVG红宝石饼图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆