简体   繁体   English

JavaScript canvas.toDataURL方法返回空白图像

[英]JavaScript canvas.toDataURL method returns blank image

I know this question has already been asked several times, however, I haven't found a solution yet. 我知道这个问题已经被问过好几次了,但是我还没有找到解决方案。

I want to take an image, rotate it and put it in a HTML canvas, to do this I'm using another canvas in which I rotate the image, this part works well, however, when I try to take the image from the second canvas using .toDataUrl, it returns a blank image. 我想拍摄一张图像,然后将其旋转并放入HTML画布中,为此,我正在使用另一张画布来旋转图像,但是这部分效果很好,但是,当我尝试从第二张中获取图像时canvas使用.toDataUrl,它将返回空白图像。 The code is the following 代码如下

  <!DOCTYPE html>
  <html>
  <head>
      <title></title>
  </head>
  <body>
  <canvas id=canvas height="400" width="400" style="border: 10px solid orange"></canvas>
  <canvas id=canvasTransform height="183" width="183" style="border: 10px solid orange"></canvas>
  <script type="text/javascript">
      //this is the canvas in which I want to put the rotated image
      var canvas=document.getElementById("canvas");
      var context=canvas.getContext("2d");

      //and I use this one to rotate it
      var canvasTransform=document.getElementById('canvasTransform');
      var contextTransform=canvasTransform.getContext("2d");

      var image=new Image(46,183);
      image.onload=function(){
        contextTransform.drawImage(image,0,0);
      }
      image.src="Fireball.png";
      console.log(image.src);
      //Now I rotate the context
      contextTransform.rotate(-0.25*Math.PI);
      //After doing this, I can see the rotated image in the second canvas, however, the following line returns a blank image
      var rotatedImageURL=canvasTransform.toDataURL();
      console.log(rotatedImageURL);
      //Finally, this part isn't wornking since I just draw a blank image
      var rotatedImage=new Image();
      rotatedImage.onload=function(){
        context.drawImage(rotatedImage,0,0);
      }
      rotatedImage.src=rotatedImageURL;

  </script>
  </body>
  </html>

I have been stuck here for a while, so any help is appreciated. 我已经在这里停留了一段时间,因此我们将不胜感激。 Thanks in advance! 提前致谢!

You likely need to wait until after drawing the image before calling toDataURL. 您可能需要等到绘制图像后再调用toDataURL。 The fireball is only drawn after the image is loaded but the rotate (and everything after that) is called right after registering the onload event handler (but before it has actually loaded). 仅在加载图像后才绘制火球,但在注册onload事件处理程序之后(但实际上未加载之前)会立即调用旋转(及其后的所有操作)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM