Created
February 7, 2014 14:40
-
-
Save tobiashm/8863760 to your computer and use it in GitHub Desktop.
Sass extension to create inline SVG gradients. Useful as a fallback for CSS gradients in IE.
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
require "base64" | |
require "rack" | |
module Sass::Script::Functions | |
def radial_gradient_image_data_url(color = Sass::Script::Color.new([0, 0, 0]), height = Sass::Script::Number.new(5)) | |
assert_type height, :Number | |
svg_data_url(<<-SVG) | |
<svg xmlns="http://www.w3.org/2000/svg"> | |
<defs> | |
<radialGradient id="gradient"> | |
<stop offset="50%" stop-color="#{svg_color(color)}" stop-opacity="0.2"/> | |
<stop offset="100%" stop-color="#{svg_color(color)}" stop-opacity="0"/> | |
</radialGradient> | |
</defs> | |
<rect width="100%" height="#{Sass::Script::Number.new(2).times(height)}" y="-#{height}" fill="url(#gradient)"></rect> | |
</svg> | |
SVG | |
end | |
declare :radial_gradient_image_data_url, [:number] | |
def linear_gradient_image_data_url(color = Sass::Script::Color.new([255, 255, 255]), height = Sass::Script::Number.new(100, ['%'])) | |
assert_type color, :Color | |
assert_type height, :Number | |
svg_data_url(<<-SVG) | |
<svg xmlns="http://www.w3.org/2000/svg"> | |
<defs> | |
<linearGradient id="gradient" x1="0" x2="0" y1="0" y2="100%"> | |
<stop offset="25%" stop-color="#{svg_color(color)}" stop-opacity="1"/> | |
<stop offset="100%" stop-color="#{svg_color(color)}" stop-opacity="0"/> | |
</linearGradient> | |
</defs> | |
<rect width="100%" height="#{height}" fill="url(#gradient)"></rect> | |
</svg> | |
SVG | |
end | |
declare :linear_gradient_image_data_url, [:color, :number] | |
protected | |
def svg_color(color) | |
"rgb(#{color.rgb.join(',')})" | |
end | |
def svg_data_url(svg) | |
base64 = Base64.encode64(svg).gsub(/\s+/, "") | |
Sass::Script::String.new("url(data:image/svg+xml;base64,#{Rack::Utils.escape(base64)})") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is now part of the sass-extras gem https://github.com/tobiashm/sass-extras