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
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
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