Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
canvasWaterMark
真的搞不定语法高亮
Owner

liyaodong commented Mar 31, 2015

addWaterMark = (_this, file) ->
  # 如果当前选项是活动报道再加水印
  $pictureType = $('#picture_type').val()
  if $pictureType == 'report'
    _this.removeFile(file)
    $('#upload-preview').modal('show')
    $previewImg = $('#upload-preview-img')
    reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onloadend = ->
      $previewImg.attr('src', reader.result)
                 .css('width', '100%')
                 .prop('crossOrigin', 'Anonymous')
      # 叠加一个水印图层上去
      $waterMark = $('#watermark')
      if $waterMark.length == 0
        $previewImg.after('<img src="'+$previewImg.data('watermark')+'"  id="watermark" crossorigin="Anonymous">')
        # 重新绑定
        $waterMark = $('#watermark')

      waterMarkConfig = {
        w: $previewImg.width()*0.3,
        t: $previewImg.height() - 75,
        l: $previewImg.width() - $previewImg.width()*0.3 - 20
      }

      $waterMark.css({
        'position': 'absolute',
        'top': waterMarkConfig.t + 'px',
        'left': waterMarkConfig.l + 'px',
        'width': waterMarkConfig.w + 'px',
        'cursor': 'move'
      }).attr('draggable', 'true')
      .draggable({containment: "parent"})

    $('#close-preview-modal').on 'click', ->
      location.reload()

    $saveSettingBtn.on 'click', ->
      $waterMark = $('#watermark')
      # 合并水印并发送到服务器端
      canvas = document.createElement('canvas')
      $(canvas).attr('id', 'waterMarkCanvas')
      ctx    = canvas.getContext('2d')

      canvas.width = file.width
      canvas.height = file.height

      ctx.drawImage(
        $previewImg.get(0), 0, 0, file.width, file.height
      )

      # 计算得到真实的水印位置
      waterMarkZoom = file.width / $previewImg.width()

      realWaterMark = {
        w: $waterMark.width() * waterMarkZoom,
        h: $waterMark.height() * waterMarkZoom,
        x: $waterMark.position().left * waterMarkZoom,
        y: $waterMark.position().top * waterMarkZoom
      }

      # 画水印到canvas
      ctx.drawImage(
        $waterMark.get(0), realWaterMark.x, realWaterMark.y,
        realWaterMark.w, realWaterMark.h
      )
      if canvas.toBlob
        canvas.toBlob (blob) ->
          temFormData = new FormData()
          temFormData.append('file', blob, file.name)
          temFormData.append 'image_type', $('#picture_type').val()
          console.log(temFormData)
          $.ajax({
           url: $uploadForm.attr('action'),
           type: "POST",
           data: temFormData,
           processData: false,
           contentType: false,
          }).done ->
            location.reload()
        ,'image/jpeg'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment