0

I created canvas where user can paste the image from clipboard. For an example, user screen shot their screen and paste in my canvas. Once pasted, user can see image pasted in the canvas. Now I want to convert my canvas to image. There is no error but when I click the button I can a empty image created. I can see there a box when i highlight the html. Below is my code and screen shot of the empty image.

Code.

<?xml version="1.0"?>
<html xmlns="http://www.w3.org/1999/xhtml">

  <script>

  function convert()
  {
  var sampleImage = document.getElementById("myCanvasElt");
  //alert(sampleImage);
  var can = convertCanvasToImage(sampleImage);
 // var apple = convertImageToCanvas(can);
  document.getElementById("testguna").appendChild(can);
  //document.getElementById("pngHolder").appendChild(apple);
  }

  // Converts image to canvas; returns new canvas element
function convertImageToCanvas(image) {
    var canvas = document.createElement("canvas").innerHTML;

    canvas.width = image.width;
    canvas.height = image.height;
    canvas.getContext("2d").drawImage(image, 0, 0);
    return canvas;
}

function convertCanvasToImage(canvas) {
    var image = new Image();
    image.src = canvas.toDataURL("image/png");
    return image;
}    
  </script>

<body>   
<h1>JavaScript Canvas Image Conversion</h1>

<h2>Original Image</h2>
<p>
<canvas id='myCanvasElt' width="100" height="100" contenteditable ="true"/>
    </p>
<h2>Canvas Image</h2>
<p id="testguna">
</p>
<h2>Canvas -&gt; PNG Image</h2>
<p id="pngHolder">
</p>
<button type="button" onClick="convert()">Click</button>    
</body>
</html>

Image enter image description here The Image i copied from W3School and paste in the canvas.

chinna_82
  • 6,353
  • 17
  • 79
  • 134

1 Answers1

0
var canvas = document.createElement("canvas").innerHTML;

gives you and empty string not a new canvas element. Its hard to draw into a string, try changing it to this.

var canvas = document.createElement("canvas");
ericjbasti
  • 2,085
  • 17
  • 19
  • Also your scope is off on the canvas element. var canvas is going to be local to the function your declaring it in. You'll need to pass it or store it at a level available to your other functions. – ericjbasti Jul 25 '13 at 20:26