Skip to content

Commit

Permalink
feat: Adds viewBox option for SVG
Browse files Browse the repository at this point in the history
Thanks to @mjy @MattDahEpic and #98 and #66
  • Loading branch information
whomwah committed Apr 22, 2021
1 parent f913e0a commit 7ac21fd
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 1 deletion.
3 changes: 3 additions & 0 deletions README.md
Expand Up @@ -92,6 +92,9 @@ shape_rendering - SVG Attribute: auto | optimizeSpeed | crispEdges | geometricPr
(defaults crispEdges)
standalone - whether to make this a full SVG file, or only an svg to embed in other svg
(default true)
viewbox - replace `svg.width` and `svg.height` attribute with `svg.viewBox` to
allow CSS scaling
(default false)
```
Example
```ruby
Expand Down
6 changes: 5 additions & 1 deletion lib/rqrcode/export/svg.rb
Expand Up @@ -16,19 +16,23 @@ module SVG
# shape_rendering - Defaults to crispEdges
# standalone - wether to make this a full SVG file, or only svg to embed
# in other svg.
# viewbox - replace `width` and `height` in <svg> with a viewBox, allows CSS scaling
#
def as_svg(options = {})
offset = options[:offset].to_i || 0
color = options[:color] || "000"
shape_rendering = options[:shape_rendering] || "crispEdges"
module_size = options[:module_size] || 11
standalone = options[:standalone].nil? ? true : options[:standalone]
viewbox = options[:viewbox].nil? ? false : options[:viewbox]

# height and width dependent on offset and QR complexity
dimension = (@qrcode.module_count * module_size) + (2 * offset)
# use dimensions differently if we are using a viewBox
dimensions_attr = viewbox ? %(viewBox="0 0 #{dimension} #{dimension}") : %(width="#{dimension}" height="#{dimension}")

xml_tag = %(<?xml version="1.0" standalone="yes"?>)
open_tag = %(<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:ev="http://www.w3.org/2001/xml-events" width="#{dimension}" height="#{dimension}" shape-rendering="#{shape_rendering}">)
open_tag = %(<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:ev="http://www.w3.org/2001/xml-events" #{dimensions_attr} shape-rendering="#{shape_rendering}">)
close_tag = "</svg>"

result = []
Expand Down
9 changes: 9 additions & 0 deletions spec/rqrcode/export_svg_spec.rb
Expand Up @@ -30,5 +30,14 @@
expect(doc).not_to match(%r{<svg.*>})
expect(doc).not_to match(%r{</svg>})
end

it "renders viewBox and not height/width when `viewbox` is `true`" do
doc = RQRCode::QRCode.new("qrcode").as_svg(viewbox: true)
# For now we do very naive pattern matching. The alternative is to
# include a librariry for parsing XML, like nokogiri. That is a big
# change for such a small test, though.
expect(doc).not_to match(%r{<\?xml.*height="\d+".*width=})
expect(doc).to match(%r{<svg.*viewBox="(\d+\s?){4}"})
end
end
end

0 comments on commit 7ac21fd

Please sign in to comment.