Javascript桌面浏览器从相机获取头像

时间:2013-07-07 14:18:06

标签: javascript ruby-on-rails html5 avatar

我在https://trello.com/找到了很酷的功能,可以从相机中加载头像。

  1. 有没有简单的方法获得&在我的rails网站上处理这个功能?
  2. 是否可以为不受支持的浏览器隐藏/处理此功能?

1 个答案:

答案 0 :(得分:2)

我制作此代码以涵盖3个案例:

  1. 从文件加载
  2. 从网址加载
  3. 从相机加载
  4. 在一个Js控件中

    @avatarUploader =
      hasGetUserMedia: ->
        !!(navigator.getUserMedia or navigator.webkitGetUserMedia or navigator.mozGetUserMedia or navigator.msGetUserMedia)
      localMediaStream: null
      stopCam: ()->
        if avatarUploader.localMediaStream
          avatarUploader.localMediaStream.stop();
      initWebCam: (picker)->
        navigator.getUserMedia = navigator.getUserMedia or navigator.webkitGetUserMedia or navigator.mozGetUserMedia or navigator.msGetUserMedia
    
        video = picker.find("video")
        canvas = picker.find("canvas")
        image = picker.find('.camera-avatar')
    
        snapshot = ->
          if avatarUploader.localMediaStream
            canvas.attr('width', video.width())
            ctx = canvas[0].getContext("2d")
            ctx.drawImage video[0], 0 , 0, video.width(), 120
            # "image/webp" works in Chrome 18. In other browsers, this will fall back to image/png.
            image.attr('src', canvas[0].toDataURL("image/jpeg"))
            picker.find('[name="avatar_data"]').val(canvas[0].toDataURL("image/png"))
    
        onFailSoHard = ->
          picker.find('.header').children().last().hide()
    
        video.on 'click', snapshot
        picker.find('.snap').on 'click', snapshot
    
        # Not showing vendor prefixes or code that works cross-browser.
        navigator.getUserMedia
          video: true
        , ((stream) ->
          video.attr('src', window.URL.createObjectURL(stream))
          avatarUploader.localMediaStream = stream
        ), onFailSoHard
        avatarUploader.webCamInited = true
      init: ()->
        picker = $('.avatar-picker')
    
        picker.on 'change', '.btn-avatar input[type=file]', ()->
          $in=$(this)
          $in.closest('.btn-avatar').find('.filename').html($in.val())
    
        picker.on 'change', '[name="option"]', ()->
          picker.find('.content').children().addClass('hide')
          picker.find('#'+$(this).val()+'-block').removeClass('hide')
          if $(this).val() == 'camera'
            avatarUploader.initWebCam(picker)
          else
            avatarUploader.stopCam()
        unless avatarUploader.hasGetUserMedia()
          picker.find('.header').children().last().hide()