0

I want to draw image in canvas and export canvas to image(jpg) file and pdf file..

It was.. click download link and popup file save dialog windows..

I have a sample source.. but good run in Chrome, but not running in IE11, IE10, IE9, IE8....


    <!DOCTYPE html>
    <html>
    <head>
        <title>toDataURL example</title>
        <style>
          canvas {
            border:solid black 1px;
          }

          img {
            width:400px;
            height:400px;
            border:solid black 1px;
          }
        </style>
    </head>
    <body>
      <h1>Copy graphic using toDataURL</h1>

      <div>
        <button id="copy">Copy canvas image to image element</button> <br />
        <canvas id="MyCanvas" width="400" height="400"  >This browser or document mode doesn't support canvas</canvas>
        <img id="MyPix" src="" width="400" height="400" />

      </div>

      <script>
        // Create some graphics on the canvas.    
        var canvas = document.getElementById("MyCanvas");
        if (canvas.getContext) {
          var ctx = canvas.getContext("2d");
          ctx.fillStyle = "white";
          ctx.beginPath();
          ctx.rect(5, 5, 300, 250);
          ctx.fill();
          ctx.stroke();
          ctx.arc(150, 150, 100, 0, Math.PI, false);
          ctx.stroke();
       }

        // catch the click from the button and copy the graphic
        document.getElementById("copy").addEventListener("click", function () {
          var canvas1 = document.getElementById("MyCanvas");
          if (canvas1.getContext) {
            var ctx = canvas1.getContext("2d");                // Get the context for the canvas.
            var myImage = canvas1.toDataURL("image/png");      // Get the data as an image.
          }
          var imageElement = document.getElementById("MyPix");  // Get the img object.
          //imageElement.src = myImage;                           // Set the src to data from the canvas.
        window.location = myImage; 


        }, false);

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

1 Answers1

0

Use the toDataUrl() function

var datImage = canvas.toDataURL("image/png");
document.write('<img src="'+datImage+'"/>');

This code will take the contents of the canvas, and turn it to a PNG image, and write it onto the screen.

Note: This does not work after you draw an image onto the canvas as it changes the data URL.

Hope this helped!

Matthew W.
  • 413
  • 1
  • 9
  • 17
  • Maybe this will help? - http://stackoverflow.com/questions/10473932/browser-html-force-download-of-image-from-src-dataimage-jpegbase64 – Matthew W. Sep 02 '14 at 23:32