嗨,我一直在尝试将画布另存为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);
 }


我想知道是否有人对为什么这样做有任何建议
先感谢您

最佳答案

给时间加载图像。加载后将其转换为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);
}

09-16 17:58