0

I am using the following JavaScript to convert an HTML5 Canvas to a .PNG image:

   function imageMe() {
        var canvasImage = document.getElementById("c");
        var img = canvasImage.toDataURL("image/png");

        document.write('<img src="' + img + '"/>');
    }

This requires the user to right click and save the image to a location.

My goal is to have the image saved to a Web Directory (overriding an image with the same name) on click without requiring the user to download and then upload an image.

My question is how do I save the image on click to the correct directory in my Website? Would I still need an Ajax file upload if I am generating an image client side, etc?

Kode
  • 3,073
  • 18
  • 74
  • 140

1 Answers1

0

If you are serving your webpage using a web server

You should use the excellent answer provided by @BhavinSolanki.

If you want to let the user save the canvas as an image on their own computer

You can use Eli Grey's FileSaverJS script: https://github.com/eligrey/FileSaver.js/

I'm not sure why, but..., the current GitHub version of FileSaverJS is not working for me (version 1.1.20150716). So for the following demo I'm using a prior version hosted on CloudFlare.com.

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var img = new Image()
img.crossOrigin = "anonymous";
img.onload = function() {
  // draw an annotated image on the canvas
  canvas.width = img.width;
  canvas.height = img.height;
  ctx.drawImage(img, 0, 0);
  ctx.fillStyle = 'black';
  ctx.fillRect(0, img.height - 30, img.width, 30);
  ctx.fillStyle = 'white';
  ctx.font = '14px verdana';
  ctx.textAlign = 'center';
  ctx.fillText('Hey, Koolaid Man!', img.width / 2, img.height - 10);
}
img.src = "https://dl.dropboxusercontent.com/u/139992952/stackoverflow/KoolAidMan.png";

// save the canvas as an image on the users local drive
$("#save").on('click', function() {
  canvas.toBlob(function(blob) {
    saveAs(blob, "KoolaidMan.png");
  });
});
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src='https://rawgit.com/eligrey/Blob.js/master/Blob.js'></script>
<script src='https://rawgit.com/eligrey/canvas-toBlob.js/master/canvas-toBlob.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2014-11-29/FileSaver.min.js'></script>

<button id="save">Save</button>
<br>
<canvas id="canvas" width=300 height=300></canvas>
markE
  • 102,905
  • 11
  • 164
  • 176