Advertisement
subarashii

confette js not mine

Mar 5th, 2015
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. NUM_CONFETTI = 350
  2. COLORS = [[85,71,106], [174,61,99], [219,56,83], [244,92,68], [248,182,70]]
  3. PI_2 = 2*Math.PI
  4.  
  5.  
  6. canvas = document.getElementById "world"
  7. context = canvas.getContext "2d"
  8. window.w = 0
  9. window.h = 0
  10.  
  11. resizeWindow = ->
  12.   window.w = canvas.width = window.innerWidth
  13.   window.h = canvas.height = window.innerHeight
  14.  
  15. window.addEventListener 'resize', resizeWindow, false
  16.  
  17. window.onload = -> setTimeout resizeWindow, 0
  18.  
  19. range = (a,b) -> (b-a)*Math.random() + a
  20.  
  21. drawCircle = (x,y,r,style) ->
  22.   context.beginPath()
  23.   context.arc(x,y,r,0,PI_2,false)
  24.   context.fillStyle = style
  25.   context.fill()
  26.  
  27. xpos = 0.5
  28.  
  29. document.onmousemove = (e) ->
  30.   xpos = e.pageX/w
  31.  
  32. window.requestAnimationFrame = do ->
  33.   window.requestAnimationFrame       ||
  34.   window.webkitRequestAnimationFrame ||
  35.   window.mozRequestAnimationFrame    ||
  36.   window.oRequestAnimationFrame      ||
  37.   window.msRequestAnimationFrame     ||
  38.   (callback) -> window.setTimeout(callback, 1000 / 60)
  39.  
  40.  
  41. class Confetti
  42.  
  43.   constructor: ->
  44.     @style = COLORS[~~range(0,5)]
  45.     @rgb = "rgba(#{@style[0]},#{@style[1]},#{@style[2]}"
  46.     @r = ~~range(2,6)
  47.     @r2 = 2*@r
  48.     @replace()
  49.  
  50.   replace: ->
  51.     @opacity = 0
  52.     @dop = 0.03*range(1,4)
  53.     @x = range(-@r2,w-@r2)
  54.     @y = range(-20,h-@r2)
  55.     @xmax = w-@r
  56.     @ymax = h-@r
  57.     @vx = range(0,2)+8*xpos-5
  58.     @vy = 0.7*@r+range(-1,1)
  59.  
  60.   draw: ->
  61.     @x += @vx
  62.     @y += @vy
  63.     @opacity += @dop
  64.     if @opacity > 1
  65.       @opacity = 1
  66.       @dop *= -1
  67.     @replace() if @opacity < 0 or @y > @ymax
  68.     if !(0 < @x < @xmax)
  69.       @x = (@x + @xmax) % @xmax
  70.     drawCircle(~~@x,~~@y,@r,"#{@rgb},#{@opacity})")
  71.  
  72.  
  73. confetti = (new Confetti for i in [1..NUM_CONFETTI])
  74.  
  75. window.step = ->
  76.   requestAnimationFrame(step)
  77.   context.clearRect(0,0,w,h)
  78.   c.draw() for c in confetti
  79. step();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement