0

下面的代码无法保存图像。

我想在单击时在画布上绘制图像,并希望在单击时使用另一个保存按钮进行保存。

<head>
    <script type="text/javascript">
    function draw()
    {
      var canvas = document.getElementById("MyCanvas");
      if (canvas.getContext) {
          var ctx = canvas.getContext("2d");                // Get the context.
          ctx.clearRect(0,0,canvas.width,canvas.height);    // Clear the last image, if it exists.
          var image = document.getElementById("pix");       // Get the address of the picture.

          ctx.drawImage(image,125,125,200,200);         
          dataURL = canvas.toDataURL("image/png");

          dataURL.onload = function () {
            ctx.drawImage(img, 0, 0);
            canvas.addEventListener("mousedown", function(event) {
                canvas.toBlob(function(blob) {
                    saveAs(blob, "exported_image.png");
                }, "image/png");
            });
        }


       }  
    }
    </script>
    </head>
    <body>
        <p>This picture will appear below.</p>
        <div>
        <img id="pix" src="http://go.microsoft.com/fwlink/?LinkID=199028" />   
        </div>
        <button onclick="draw()">Draw Images on canvas</button> 
      <canvas id="MyCanvas" width="600" height="500"> </canvas>
    </body>
    </html> 
4

1 回答 1

0

您绘制可能尚未加载的图像,在画布上绘制图像之前使用 onload() 函数:

     var image = document.getElementById("pix");       // Get the address of the picture.
     image.onload = function() { //ADD THIS LINE TO YOUR CODE
      ctx.drawImage(image,125,125,200,200);  
     };
于 2012-09-04T13:34:09.080 回答