1

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

  1. 有没有简单的方法可以在我的 Rails 站点上获取和处理此功能?
  2. 是否可以为不支持的浏览器隐藏/处理此功能?
4

1 回答 1

2

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

  1. 从文件加载
  2. 从网址加载
  3. 从相机加载

在一个 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()
于 2013-08-31T19:07:49.780 回答