Posted by Sandro Paganotti in
Ruby on Rails -
4 comments
Today we’re going to discover two ways to create vectorial graphic with Ruby;
RVG
The first way is called RVG and it’s part of the well-known Rmagick library. With RVG you can create custom shapes and then render them to images. Here there is a simple example (taken from the RMagic docs and modified a bit):
require 'rvg/rvg'
target = Magick::RVG.new.viewbox(0,0,200,200) do |targ|
targ.g.styles(:stroke_width=>20, :stroke=>'#ff5600', :fill=>'#abd600') do |grp|
grp.circle(90, 100, 100)
grp.circle(60, 100, 100)
grp.circle(30, 100, 100)
end
end
rvg = Magick::RVG.new(258, 100) do |canvas|
canvas.use(target, 0, 0, 100, 100)
canvas.use(target, 100, 16.6667, 66.7, 66.7)
canvas.use(target, 166.6667, 25, 50, 50)
canvas.use(target, 216.6667, 30, 40, 40)
end
rvg.draw.write('nested_rvg.gif')
And this is its output:
SvuGy
This library acts in a very similar way with the small but noticeable difference that its output is not an image but a pure .svg file. Here is the code to product the same sample as above ( I know, it is not so DRY but i didn’t find smarter ways to do this, in part due to a lack of documentation):
require 'SVuGy'
drawing1 = SVuGy::Document.new(530, 200) do
tri = group.style(:stroke_width=>20, :stroke=>'#ff5600', :fill=>'#abd600'){
el2 = ellipse(100, 100, 90, 90)
el1 = ellipse(100, 100, 60, 60)
el0 = ellipse(100, 100, 30, 30)
}
tri2 = group.style(:stroke_width=>20, :stroke=>'#ff5600', :fill=>'#abd600').translate(200,30).scale(0.66){
el2 = ellipse(100, 100, 90, 90)
el1 = ellipse(100, 100, 60, 60)
el0 = ellipse(100, 100, 30, 30)
}
tri3 = group.style(:stroke_width=>20, :stroke=>'#ff5600', :fill=>'#abd600').translate(330,50).scale(0.5){
el2 = ellipse(100, 100, 90, 90)
el1 = ellipse(100, 100, 60, 60)
el0 = ellipse(100, 100, 30, 30)
}
tri4 = group.style(:stroke_width=>20, :stroke=>'#ff5600', :fill=>'#abd600').translate(430,60).scale(0.4){
el2 = ellipse(100, 100, 90, 90)
el1 = ellipse(100, 100, 60, 60)
el0 = ellipse(100, 100, 30, 30)
}
end
print drawing1.to_svg
And here you can admire the generated SVG (download the file):
Considerations
Now that I found out this library I’m thinking about an hypothetic world where these two libraries works with the same syntax letting you generate SVG if the browser support this format and otherwise printing a simple image. Another big improvement could be create a SVG to RVG parser, by this way you can import complex SVGs generated with WYSIWYG programs and then add to them dynamic functionalities.
Permalink