将画布保存为png

时间:2014-01-30 11:30:04

标签: javascript html5 canvas

您好,我一直在尝试将我的画布保存为png,并在编译完成后立即将其生成到网页。我遇到的问题是,当图像被保存并输出时,它只显示我从文本框加载的文本。我还加载了一个背景图像,该图像显示在画布中但不显示在输出图像中。

<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脚本

    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);  
 }

我想知道是否有人有任何关于为什么会这样做的建议 提前谢谢

1 个答案:

答案 0 :(得分:3)

给自己加载图片的时间。当它被加载然后将其转换为DataUrl。

试试这个:

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

 imageObj.src ='132.png';

加载图像后,请调用:

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);  
}