Skip to content

Instantly share code, notes, and snippets.

@theuntitled
Last active August 29, 2015 14:03
Show Gist options
  • Save theuntitled/4176681e28774665506e to your computer and use it in GitHub Desktop.
Save theuntitled/4176681e28774665506e to your computer and use it in GitHub Desktop.
Generates an inline svg with the specified styles
require File.join(File.dirname(__FILE__), 'inline-svg.rb');
# ... your stuff
Display the source blob
Display the rendered blob
Raw
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 64 64">
<style>
.st2{fill:none;stroke:#000;stroke-miterlimit:10;}
</style>
<g id="watch-dogs">
<path class="st2" d="M23.4,33.7l-7.8,10.7c0,0-0.1,0-0.1,0V14.8c0-0.1,0.1-0.1,0.1,0l16.6,40.8c0,0,0.1,0,0.1,0l16-40.8
c0-0.1,0.1,0,0.1,0v29.6c0,0.1-0.1,0.1-0.1,0l-16-23.8c0,0-0.1,0-0.1,0L23.4,33.7z"/>
</g>
<g id="hr">
<line class="st2" x1="45.1" y1="39.5" x2="19.2" y2="39.5"/>
</g>
<g id="circle">
<path class="st2" d="M61.8,42.4C69.9,17.1,46.9-5.9,21.6,2.2C12.4,5.2,5.2,12.4,2.2,21.6
c-8.1,25.3,14.9,48.3,40.2,40.2C51.6,58.8,58.8,51.6,61.8,42.4z"/>
</g>
</svg>
require 'sass'
require 'base64'
module Sass::Script::Functions
def inlineSvg(string, list = Sass::Script::List.new(Array.new, :comma))
assert_type string, :String
file = File.open(string.value, "rb")
svgFileContents = file.read
file.close
cssString = ''
actualList = list.to_a
if actualList.length > 0
cssString = '<style type="text/css">circle,ellipse,line,path,polygon,polyline,rect,text{'
if actualList.length > 2
actualList.each { |pair|
cssString = cssString + pair.to_s.sub(' ', ': ') + ' !important;'
}
else
cssString = cssString + actualList.at(0).to_s + ': ' + actualList.at(1).to_s + ' !important;'
end
cssString = cssString + '}</style>';
end
svgFileContents = svgFileContents.sub('</svg>', cssString + '</svg>');
return Sass::Script::String.new('url(\'data:image/svg+xml;charset=utf-8;base64,' + Base64.encode64(svgFileContents) + '\')')
end
end
.svg-stuff {
width: 100px;
height: 100px;
display: block;
background: inlineSvg('image.svg', (stroke #000));
&:hover {
background: inlineSvg('image.svg', (fill rgba(0, 0, 255, .5), stroke #f00));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment