anam
anam

Reputation: 3913

save canvas as an image on local machine

I am trying to save canvas on my local machine but nothing is working . please check below code .

    <!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }

    </style>

  <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
  </head>

  <body>
    <canvas id="myCanvas" width="578" height="400"></canvas>
    <img id="canvasImg" alt="Right click to save me!">
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');


       var imageObj = new Image();

      imageObj.onload = function() {
        context.drawImage(imageObj, 69, 50);

       // 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();
      };
      imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';

      var imageData = canvas.toDataURL();


    </script>
  </body>
</html>

in this example code i am draing some image and cloud and wish to save it as as image file ???

Upvotes: 1

Views: 546

Answers (2)

m0sk1t
m0sk1t

Reputation: 31

Try send your imageData to server via XMLHTTPRequest or fetch. Something like this:

const canvas = document.getElementById('cvs');
const context = canvas.getContext('2d');
context.font = '26pt Arial';
context.fillText('Some example text!', 10, 40);

url = canvas.toDataURL();
fetch('/yoururl', { method: 'POST', body: new FormData(url)})
.then(res => console.log(res))

Maybe this link helps too

Upvotes: 0

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93561

As Sacho mentioned, 'tainting a canvas stops it being saved. This is a security feature to stop data from third-party websites being captured.

One workaround is to serve up all static images from your own website. This can be done by having your server download the image on request from the third-party site and return the data stream (as if it was on your own domain). Then the browser has no complaints about tainting as it is effectively from your server.

I have no idea what your server-side technology is, so can't suggest a specific implementation, but you basically could generate requests like:

/imagerequest.php?url=http%3A%2F%2Fwww.html5canvastutorials.com%2Fdemos%2Fassets%2Fdarth-vader.jpg

Where the source URL is provided as a parameter and imagerequest.php (or aspx) etc is your server script.

Upvotes: 1

Related Questions