Skip to content

Instantly share code, notes, and snippets.

@jimjeffers
Created May 22, 2011 18:11
Show Gist options
  • Save jimjeffers/985722 to your computer and use it in GitHub Desktop.
Save jimjeffers/985722 to your computer and use it in GitHub Desktop.
Generate noise with Canvas.
# Inspired and largely borrowed from Pixstatic
# http://www.pixastic.com/lib/git/pixastic/actions/noise.js
# https://github.com/jseidelin/pixastic
# And NetTuts tutorial:
# http://blip.tv/nettuts/how-to-generate-image-noise-with-canvas-4439977#EpisodeDescription
# http://net.tutsplus.com/tutorials/javascript-ajax/how-to-generate-noise-with-canvas/
window.Noise = class Noise
constructor: ->
@width = 100
@height = 100
@amount = 0.5
@strength = 0.5
@mono = false
@opacity = 1
@canvas = document.createElement("canvas")
@ctx = @canvas.getContext("2d")
generate: ->
# Don't do anything if the browser doesn't have canvas.
return false if !Modernizr.canvas
@canvas.width = @width
@canvas.height = @height
amount = @normalize(@amount)
strength = @normalize(@strength)
noise = 128 * strength
y = @height
random = Math.random
while --y
x = @width
while --x
if random() < amount
color =
r: 0
g: 0
b: 0
if @mono
pxlNoise = random()*noise;
color.r = @normalizeColor(pxlNoise)
color.g = @normalizeColor(pxlNoise)
color.b = @normalizeColor(pxlNoise)
else
color.r = @normalizeColor(random()*noise)
color.g = @normalizeColor(random()*noise)
color.b = @normalizeColor(random()*noise)
@ctx.fillStyle = "rgba(#{color.r},#{color.g},#{color.b},#{@opacity})"
@ctx.fillRect(x,y,1,1)
# Force to any amount between 0 and 1
normalize: (value) ->
Math.max(0,Math.min(1,value))
# Force value to any amount between 0 and 255.
normalizeColor: (value) ->
Math.floor(Math.max(0,Math.min(255,value)))
toCSS: ->
"url(#{@canvas.toDataURL("image/png")})"
# Example usage...
noise = new Noise
noise.generate()
$("body").css("background-image",noise.toCSS())
# or tweak your settings
noise.height = 200
noise.width = 200
noise.strength = 0.1
noise.amount = 0.1
noise.opacity = 0.1
noise.generate()
$("body").css("background-image",noise.toCSS())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment