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

后端 未结 8 2221
走了就别回头了
走了就别回头了 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:26

    Here is an example of how to achieve what you need:

    1. Draw something (taken from canvas tutorial)

    
    

    1. Convert canvas image to URL format (base64)

      var dataURL = canvas.toDataURL();

    2. Send it to your server via Ajax

        $.ajax({
          type: "POST",
          url: "script.php",
          data: { 
             imgBase64: dataURL
          }
        }).done(function(o) {
          console.log('saved'); 
          // If you want the file to be visible in the browser 
          // - please modify the callback in javascript. All you
          // need is to return the url to the file, you just saved 
          // and than put the image in your browser.
        });

    1. Save base64 on your server as an image (here is how to do this in PHP, the same ideas is in every language. Server side in PHP can be found here):

提交回复
热议问题