Skip to content

Instantly share code, notes, and snippets.

Created March 5, 2011 18:24
Show Gist options
  • Save aaronrussell/856571 to your computer and use it in GitHub Desktop.
Save aaronrussell/856571 to your computer and use it in GitHub Desktop.
Sass implementation of the Noisy jquery plugin:
require "rubygems"
require "chunky_png"
require "base64"
module Sass::Script::Functions
def background_noise(c, noise = 0.5, opacity = 0.08, size = 200, mono = false)
# Convert SASS numbers to Ruby classes
noise = noise.to_s.to_f if noise.is_a? Sass::Script::Number
opacity = opacity.to_s.to_f if opacity.is_a? Sass::Script::Number
size = size.to_i if size.is_a? Sass::Script::Number
mono = mono.to_bool if mono.is_a? Sass::Script::Bool
# Create the background image
bg_color = ChunkyPNG::Color.rgba(,,, (c.alpha * 255).round)
bg_image =, size, bg_color)
# Create a transparent foreground image
fg_image =, size)
# Add some noise to the foreground image
for i in (0..(noise * (size**2)))
x = rand(size.to_i)
y = rand(size.to_i)
r = rand(255)
a = rand(255 * opacity)
color = mono ? ChunkyPNG::Color.rgba(r, r, r, a) : ChunkyPNG::Color.rgba(r, rand(255), rand(255), a)
fg_image.set_pixel(x, y, color)
# Mix it up
image = bg_image.compose(fg_image)
# Save the image - will eventually save to a file but for now
# a base64 data url will do...
data = Base64.encode64(image.to_blob).gsub("\n", "")"url('data:image/png;base64,#{data}')")
$bg-noise-intensity-default: 0.5;
$bg-noise-opacity-default: 0.08;
$bg-noise-size-default: 200;
@mixin bg-noise($color,
$intensity: $bg-noise-intensity-default,
$opacity: $bg-noise-opacity-default,
$size: $bg-noise-size-default,
$mono: false
background-color: $color;
background-image: background_noise($color, $intensity, $opacity, $size, $mono);
background-repeat: repeat;
@mixin bg-noise-mono($color,
$intensity: $bg-noise-intensity-default,
$opacity: $bg-noise-opacity-default,
$size: $bg-noise-size-default
@include bg-noise($color, $intensity, $opacity, $size, true);
body {
@include bg-noise(#cecece);
Copy link

Awesome! I love it. Exactly the kind of noise I was hoping for. You should definition make a small gem out of this will be super valuable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment