Closed. This question needs to be more focused。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?更新问题,使其仅通过editing this post专注于一个问题。
                        
                        5年前关闭。
                                                                                            
                
        
我在https://trello.com/找到了很酷的功能,可以从相机加载头像。


在我的Rails网站上,有没有简便的方法来获取和处理此功能?
是否可以为不支持的浏览器隐藏/处理此功能?

最佳答案

我编写此代码来涵盖3重案例:


从文件加载
从网址加载
从相机加载


一站式控制

@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()

关于javascript - Javascript桌面浏览器从相机获取头像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17512925/

10-13 00:24