tomtom
tomtom

Reputation: 13

Saving canvas as a png

Hi there I have been trying to save my canvas as a png and generate it to the web page as soon as it is complied. The problem i am having is that when the image is saved and outputted it only shows the text that i load in from a text box. I also load in a background image which shows in the canvas but not in the outputted image.

<form>
<input name="name" id="name" type="text"/>
</form>
<canvas id="myCanvas" width="640" height="480"></canvas>
<input name="" type="button" onclick="save()" /> Generate

<div id="sample">
</div>
<script type="text/javascript" src="canvas.js"></script>

java script

    var myCanvasElement=document.getElementById("myCanvas");
    var drawingContext=myCanvasElement.getContext("2d");

    // clear canvas and div
    drawingContext.clearRect ( 0 , 0 , 640 , 480 );
    document.getElementById("sample").innerHTML = "";

     // add text box text to canvas
     var amount1 = document.getElementById("name").value;
     drawingContext.font = "bold 12px sans-serif"; 
     drawingContext.fillText(amount1, 30, 43); 
     drawingContext.fillText(amount1, 30, 43); 

     //loads in image to canvas

     var imageObj = new Image();
     imageObj.onload = function() {
     drawingContext.drawImage(imageObj, 100, 150);
     };
     imageObj.src ='132.png';

     //converts canvas to image 
     var canvas = document.getElementById('myCanvas'),
     dataUrl = canvas.toDataURL(),
     imageFoo = document.createElement('img');
     imageFoo.src = dataUrl;

     //Style your image here
     imageFoo.style.width = '640px';
     imageFoo.style.height = '480px';

     //After you are done styling it, append it to the BODY element
     var theDiv = document.getElementById("sample");
     theDiv.appendChild(imageFoo);  
 }

I was wondering if anyone had any suggestions as to why it might be doing this Thank you in advance

Upvotes: 1

Views: 392

Answers (1)

SeeTheC
SeeTheC

Reputation: 1631

Give time to load the image . when its is loaded then convert it to DataUrl.

Try this :

  // your code
  var imageObj = new Image();
     imageObj.onload = function() {
        drawingContext.drawImage(imageObj, 100, 150);
         setTimeout(loadImage,200)    ;
     };

 imageObj.src ='132.png';

After image is loaded call this :

function loadImage()
{
     //converts canvas to image 
     var canvas = document.getElementById('myCanvas'),
     dataUrl = canvas.toDataURL(),
     imageFoo = document.createElement('img');
     imageFoo.src = dataUrl;

     //Style your image here
     imageFoo.style.width = '640px';
     imageFoo.style.height = '480px';

     //After you are done styling it, append it to the BODY element
     var theDiv = document.getElementById("sample");
     theDiv.appendChild(imageFoo);  
}

Upvotes: 3

Related Questions