Chanter
Chanter

Reputation: 109

Javascript: Saving from canvas not functioning

I am new at javascript and I am trying to save a signature from canvas. When I click the Submit button a new window is suppose to open in the browser and save the contents of the canvas but this is not working. I have checked the isset to make sure that the button is working.

Code:

<?php
            if(isset($_POST['submit']))
            {
                ?>
                        <script>
                            var canvas = document.getElementById("canvas");
                            var w=window.open('about:blank','image from canvas');
                            w.document.write("<img src='"+canvas.toDataURL("image/png")+"' alt='from canvas'/>");
                        </script>
        <?php
            }
        ?>

Upvotes: 0

Views: 56

Answers (1)

Thomas Wikman
Thomas Wikman

Reputation: 705

You could do something like this. Pull the base64 image from the canvas, post it to a backend, handle result (in front end).

// IGNORE (DRAW STUFF)
  // Source: http://www.html5canvastutorials.com/advanced/html5-canvas-get-image-data-url/
  var canvas = document.getElementById('canvas');
  var context = canvas.getContext('2d');

  // draw cloud
  context.beginPath();
  context.moveTo(170, 80);
  context.bezierCurveTo(130, 100, 130, 150, 230, 150);
  context.bezierCurveTo(250, 180, 320, 180, 340, 150);
  context.bezierCurveTo(420, 150, 420, 120, 390, 100);
  context.bezierCurveTo(430, 40, 370, 30, 340, 50);
  context.bezierCurveTo(320, 5, 250, 20, 250, 50);
  context.bezierCurveTo(200, 5, 150, 20, 170, 80);
  context.closePath();
  context.lineWidth = 5;
  context.fillStyle = '#8ED6FF';
  context.fill();
  context.strokeStyle = '#0000ff';
  context.stroke();
  // STOP IGNORING
<canvas id="canvas" width="600" height="200"></canvas>
<button onclick="sendImageToBackend()">Send it to backend!</button>
<script>
  function getCanvasImage() {
    var canvas = document.getElementById('canvas');
    return (canvas) ? canvas.toDataURL('image/png') : false;
  }

  function sendImageToBackend() {
    var url = 'save.php';
    var dataURL = getCanvasImage();
    var xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.onload = function () {
      var responseImg;
      // Handle response from save.php
      if (this.status === 200) {
        responseImg = document.createElement('IMG');
        responseImg.src = this.responseText;
        document.body.appendChild(responseImg);
      } else {
        console.log('Errorz happened!', this.responseText);
      }
    };
    xhr.send('data=' + encodeURIComponent(dataURL));
  }
</script>

save.php

<?php
if ($_REQUEST['data']) {
  http_response_code(200); // OK
  echo "{$_REQUEST['data']}";
} else {
  http_response_code(400); // Bad request
  echo "Oh, noes! You brokez it!";
}

Upvotes: 2

Related Questions