How to save an HTML5 Canvas as an image on a server?

后端 未结 8 2220
走了就别回头了
走了就别回头了 2020-11-21 23:50

I\'m working on a generative art project where I would like to allow users to save the resulting images from an algorithm. The general idea is:

  • Create an image
8条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 00:38

    I think you should tranfer image in base64 to image with blob, because when you use base64 image, it take a lot of log lines or a lot of line will send to server. With blob, it only the file. You can use this code bellow:

    dataURLtoBlob = (dataURL) ->
      # Decode the dataURL
      binary = atob(dataURL.split(',')[1])
      # Create 8-bit unsigned array
      array = []
      i = 0
      while i < binary.length
        array.push binary.charCodeAt(i)
        i++
      # Return our Blob object
      new Blob([ new Uint8Array(array) ], type: 'image/png')
    

    And canvas code here:

    canvas = document.getElementById('canvas')
    file = dataURLtoBlob(canvas.toDataURL())
    

    After that you can use ajax with Form:

      fd = new FormData
      # Append our Canvas image file to the form data
      fd.append 'image', file
      $.ajax
        type: 'POST'
        url: '/url-to-save'
        data: fd
        processData: false
        contentType: false
    

    This code using CoffeeScript syntax.

    if you want to use javascript, please paste the code to http://js2.coffee

提交回复
热议问题