Skip to content

Instantly share code, notes, and snippets.

@bangpound
Created April 24, 2010 20:08
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bangpound/377912 to your computer and use it in GitHub Desktop.
Save bangpound/377912 to your computer and use it in GitHub Desktop.
Cross-browser translucent backgrounds. Creates RGBa PNG files at compile time.
# bangpound does not know Ruby.
#
# inspired by http://www.alloycode.com/2009/6/19/fun-with-rmagick
#
# RGBa PNG method described at http://leaverou.me/2009/02/bulletproof-cross-browser-rgba-backgrounds/
module Sass::Script::Functions
def rgbapng(color)
require 'rubygems'
require "RMagick"
assert_type color, :Color
image = Magick::Image.new(1, 1) {
self.background_color = color.to_s
}
colorstring = color.red.to_i.to_s(16).rjust(2, '0')
colorstring += color.green.to_i.to_s(16).rjust(2, '0')
colorstring += color.blue.to_i.to_s(16).rjust(2, '0')
colorstring += (color.alpha * 255).to_i.to_s(16).rjust(2, '0')
path = File.join("rgbapng", colorstring + ".png");
real_path = File.join(Compass.configuration.images_path, path);
if !File.exists?(real_path) || options[:force]
puts "Writing #{path}"
image.write(real_path)
end
Sass::Script::String.new(path)
end
def rgbapng_inline(color)
require 'rubygems'
require "RMagick"
require 'base64'
assert_type color, :Color
image = Magick::Image.new(1, 1) {
self.background_color = color.to_s
self.format = "PNG"
}
data = Base64.encode64(image.to_blob).gsub("\n","")
Sass::Script::String.new("url('data:image/png;base64,#{data}')")
end
end
# Usage in a mixin.
#
# =rgba-background($color)
# background: image_url(rgbapng($color))
# background: $color
#
# Add mixin to a style.
#
# .block-region
# +rgba-background(rgba(255, 255, 0, 0.7))
#
# Compiles to this CSS
#
# .block-region {
# background: url('../images/rgbapng/ffff00b2.png?1272139839');
# background: rgba(255, 255, 0, 0.7); }
# Inline usage
#
# .block-region
# background: rgbapng_inline(rgba(255, 255, 0, 0.7))
# background: rgba(255, 255, 0, 0.7)
#
# Compiles to:
#
# .block-region {
# background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABEAYAAABPhRjKAAAABmJLR0T/////AAC3fuUjAAAACXBIWXMAAABIAAAASABGyWs+AAAAEUlEQVQI12P4////fwaGzUYAG4cE4jr+6PkAAAAASUVORK5CYII=');
# background: rgba(255, 255, 0, 0.7); }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment