Class: FoggyMirror::SVG

Inherits:
Exporter show all
Defined in:
lib/foggy-mirror/exporters/svg.rb

Constant Summary collapse

XML_HEADER =
'<?xml version="1.0" encoding="UTF-8"?>'
ID_START =
'a'
VIEWBOX_SIZE =
1000
STRATEGIES =
%i[embedded_image gradients]

Instance Method Summary collapse

Methods inherited from Exporter

#initialize

Constructor Details

This class inherits a constructor from FoggyMirror::Exporter

Instance Method Details

#circlesObject



41
42
43
44
45
46
47
# File 'lib/foggy-mirror/exporters/svg.rb', line 41

def circles
  blobs.map.with_index do |b, i|
    id = color_ids[b.color]
    x, y, r = [b.x, b.y, b.r].map { |c| (c * VIEWBOX_SIZE).to_i }
    %{<circle cx="#{x}" cy="#{y}" r="#{r}" fill="url(##{id})"/>}
  end
end

#color_idsObject



49
50
51
52
53
54
55
# File 'lib/foggy-mirror/exporters/svg.rb', line 49

def color_ids
  @color_ids ||=
    begin
      id = String.new(ID_START)
      Hash[blobs.map(&:color).uniq.map { |c| [c, id.dup].tap { id.succ! } }]
    end
end

#headerObject



31
32
33
# File 'lib/foggy-mirror/exporters/svg.rb', line 31

def header
  %{#{XML_HEADER}<svg width="#{VIEWBOX_SIZE}" height="#{VIEWBOX_SIZE}" preserveAspectRatio="none" viewBox="0 0 #{VIEWBOX_SIZE} #{VIEWBOX_SIZE}" xmlns="http://www.w3.org/2000/svg" version="1.1" style="background-color:#{base_color}">}
end

#radial_gradientsObject



35
36
37
38
39
# File 'lib/foggy-mirror/exporters/svg.rb', line 35

def radial_gradients
  color_ids.map do |color, id|
    %{<radialGradient id="#{id}"><stop offset="0" stop-color="#{color}"/><stop offset="100%" stop-color="#{color}" stop-opacity="0"/></radialGradient>}
  end
end

#render(strategy: STRATEGIES.first) ⇒ Object



13
14
15
16
17
18
19
20
21
# File 'lib/foggy-mirror/exporters/svg.rb', line 13

def render(strategy: STRATEGIES.first)
  strategy = STRATEGIES.first if strategy.nil?

  unless STRATEGIES.include?(strategy.to_sym)
    raise ArgumentError, "Invalid SVG rendering strategy `#{strategy}'"
  end

  send("render_#{strategy}")
end

#render_embedded_imageObject



27
28
29
# File 'lib/foggy-mirror/exporters/svg.rb', line 27

def render_embedded_image
  "#{header}#{blur_filter}#{embedded_image}</svg>"
end

#render_gradientsObject



23
24
25
# File 'lib/foggy-mirror/exporters/svg.rb', line 23

def render_gradients
  "#{header}<defs>#{radial_gradients.join}</defs>#{circles.join}</svg>"
end