Skip to content

Instantly share code, notes, and snippets.

@leemartin
Created January 25, 2013 17:33
Show Gist options
  • Save leemartin/4636346 to your computer and use it in GitHub Desktop.
Save leemartin/4636346 to your computer and use it in GitHub Desktop.
WebRTC Sprites Generator
$ ->
# Variables
photo = 0
size = 150
directions =
center: { x: size, y: size, i: "straight ahead" }
north: { x: size, y: 0, i: "up" }
northwest: { x: 0, y: 0, i: "up over your right shoulder" }
west: { x: 0, y: size, i: "right" }
southwest: { x: 0, y: size * 2, i: "at your right shoulder" }
south: { x: size, y: size * 2, i: "at your chest" }
southeast: { x: size * 2, y: size * 2, i: "at your left shoulder" }
east: { x: size * 2, y: size, i: "left" }
northeast: { x: size * 2, y: 0, i: "up over your left shoulder" }
# App
App =
init: ->
@canvas = document.createElement("canvas")
@canvas.setAttribute("width", size * 3)
@canvas.setAttribute("height", size * 3)
@context = @canvas.getContext("2d")
@instructions = $("#instructions")
@sprite = $("#sprite")
getUserMedia(@options, @success, @error)
options:
audio : false
video : true
el : "webcam"
extern : null
append : true
noFallback : true
width : 320
height : 240
mode : "callback"
success: (stream) ->
if App.options.context is "webrtc"
video = App.options.videoEl
if (typeof MediaStream isnt "undefined" && MediaStream isnt null) && stream instanceof MediaStream
if video.mozSrcObject isnt undefined
video.mozSrcObject = stream
else
video.src = stream
video.play()
else
vendorURL = window.URL or window.webkitURL
video.src = if vendorURL then vendorURL.createObjectURL(stream) else stream
App.instructions.text("Look straight ahead and press spacebar.")
error: (error) ->
console.error("An error occured: [CODE #{ error.code }]")
takePhoto: () ->
if photo < 8
v = document.getElementsByTagName("video")[0]
h = v.videoHeight
w = v.videoWidth
x = (w - h) / 2
d = directions[ _.keys(directions)[photo] ]
App.context.drawImage(v, x, 0, h, h, d.x, d.y, size, size)
if photo isnt 8
next = directions[ _.keys(directions)[photo + 1] ]
App.instructions.text("Look #{ next.i } and press spacebar.")
photo += 1
else
App.sprite.css
"background": "url(#{ App.canvas.toDataURL('image/png') })"
App.instructions.text("Done! Try pressing your arrow keys.")
pointFace: (d) ->
App.sprite.css
"background-position": "-#{ directions[d].x }px -#{ directions[d].y }px"
# Controls
$(window).keydown (e) ->
switch e.keyCode
when 32
App.takePhoto()
when 38
App.pointFace("north")
when 39
App.pointFace("east")
when 40
App.pointFace("south")
when 37
App.pointFace("west")
$(window).keyup (e) ->
App.pointFace("center")
# Initialize
App.init()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment