Last active
March 30, 2016 17:52
-
-
Save jamesduncombe/1cfd04edb5ef53a6d7f1 to your computer and use it in GitHub Desktop.
Quick and dirty SVG icon spriter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# | |
# Sprites SVG icons into a single output | |
# | |
# Sample output which you'd put in the page: | |
# | |
# <svg version="1.1" xmlns="http://www.w3.org/2000/svg" style="display: none;"> | |
# <symbol id="icon-name" viewBox="0 0 76.7 89.6"> | |
# <path d="M71.2,28.1c-3,0-5.5,2.5-5.5" /> | |
# </symbol> | |
# ... | |
# </svg> | |
# | |
# Elsewhere on your page where you want the icon to show: | |
# | |
# <svg> | |
# <use xlink:href="#icon-name"></use> | |
# </svg> | |
# | |
# 'icon-name' is replaced with the name of the source icon file... | |
# | |
# Usage: ./svgripper.rb ./path/to/svg_icons > output.svg | |
# | |
# Inspired from: https://css-tricks.com/svg-symbol-good-choice-icons/ | |
# | |
# Todo: | |
# - Add support for other elements such as circle, defs etc | |
# | |
require 'nokogiri' | |
require 'open-uri' | |
def parser(x) | |
x.css('path').each do |path| | |
puts %Q{<path d="#{path.attribute('d').to_s.gsub(/\s/, '')}" />} | |
end | |
x.css('polygon').each do |path| | |
puts %Q{<polygon points="#{path.attribute('points')}" />} | |
end | |
x.css('rect').each do |path| | |
puts %Q{<rect x="#{path.attribute('x')}" y="#{path.attribute('y')}" width="#{path.attribute('width')}" height="#{path.attribute('height')}" />} | |
end | |
end | |
puts %Q{<svg version="1.1" xmlns="http://www.w3.org/2000/svg" style="display: none;">} | |
Dir[ARGV[0]].each do |file| | |
# open, parse, close | |
f = File.open(file, 'r') | |
x = Nokogiri.parse(f.read) | |
f.close | |
# create the viewbox | |
view_box = x.css('svg').attribute('viewBox').value | |
# open the symbol | |
puts %Q{ <symbol id="#{File.basename(file, '.*')}" viewBox="#{view_box}">} | |
# pull out needed things | |
if (x.css('g[transform]').any?) | |
x.css('g[transform]').each do |path| | |
puts %Q{ <g transform="#{path.attribute('transform')}">} | |
parser(path) | |
puts %Q{ </g>} | |
end | |
else | |
parser(x) | |
end | |
puts %Q{</symbol>} | |
end | |
# close it | |
puts "</svg>" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment