diff --git a/README.md b/README.md index 7c246d8..3a9e4aa 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/lib/rqrcode/export/svg.rb b/lib/rqrcode/export/svg.rb index a4d2aea..cd3fa70 100644 --- a/lib/rqrcode/export/svg.rb +++ b/lib/rqrcode/export/svg.rb @@ -16,6 +16,7 @@ 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 with a viewBox, allows CSS scaling # def as_svg(options = {}) offset = options[:offset].to_i || 0 @@ -23,12 +24,15 @@ def as_svg(options = {}) 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 = %() - open_tag = %() + open_tag = %() close_tag = "" result = [] diff --git a/spec/rqrcode/export_svg_spec.rb b/spec/rqrcode/export_svg_spec.rb index 281ea55..286da62 100644 --- a/spec/rqrcode/export_svg_spec.rb +++ b/spec/rqrcode/export_svg_spec.rb @@ -30,5 +30,14 @@ expect(doc).not_to match(%r{}) expect(doc).not_to match(%r{}) 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{