0 Replies Latest reply on Jul 8, 2016 2:02 PM by chadd88045137

    How to upload a canvas image into a web app?

    chadd88045137 Level 1

      Hello all. I've been stuck on this for almost 3 weeks!. I basically want to be able to upload an image an user created on the canvas element. I know this is a javascirpt question but its not that many business catalyst users on stackoverflow

       

      html.

       

      <form name="catcustomcontentform20321" onsubmit="myContactSubmit()" enctype="multipart/form-data" method="post" action="/CustomContentProcess.aspx?CCID=40140&amp;OID={module_oid}&amp;OTYPE={module_otyp e}" id="js-contact">

      <input class="cat_textbox_small" type="text" name="ItemName" id="ItemName" maxlength="255" />

      <input type="file" name="CAT_Custom_6" id="CAT_Custom_6" class="cat_textbox" />

      </form>

      <canvas id="demo" width="200" height="200"></canvas>

      <input class="upload" type="submit" value="Submit" id="catbutton">

      The JavaScript.

      function init() {

              var canvas = document.getElementById('demo');

              var ctx = canvas.getContext('2d');

              drawDemo(ctx);

          }

      $(function() {

      init();

          $('.upload').click(function(){

              var formData = new FormData($('form')[0]);

              $.ajax({

                  url: '/CustomContentProcess.aspx?CCID=40140&amp;OID={module_oid}&amp;OTYPE={module_otype}',

                  type: 'POST',

                  xhr: function() {

                   myXhr = $.ajaxSettings.xhr();

                  var dataURI = canvas.toDataURL();

                  var blob = dataURItoBlob(dataURI);

                  formData.append('CAT_Custom_6', blob);

                  myXhr.open('POST', '/CustomContentProcess.aspx?CCID=40140&amp;OID={module_oid}&amp;OTYPE={module_otype}', true);

                  myXhr.send(formData);

      },

                  success: function(results){

                   console.log(results);

                  },

                  data: formData,

                  cache: false,

                  contentType: false,

                  processData: false

              });

          });

         });

      function drawDemo(ctx) {

              ctx.fillRect(25,25,100,100);

              ctx.clearRect(45,45,60,60);

              ctx.strokeRect(50,50,50,50);

          }

         function dataURItoBlob(dataURI) {

      var byteString = atob(dataURI.split(',')[1]);

      var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

      var ab = new ArrayBuffer(byteString.length);

      var dw = new DataView(ab);

      for(var i = 0; i < byteString.length; i++) {

        dw.setUint8(i, byteString.charCodeAt(i));

              }

      return new Blob([ab], {type: mimeString});

          }