我知道这个问题已经被多次询问了,但是,我还没有 找到了解决方案。
我想拍摄一张图片,将其旋转并放入HTML画布中,为了做到这一点我使用另一个旋转图像的画布,这部分效果很好但是,当我尝试拍摄时使用.toDataUrl从第二个画布中获取图像,它返回一个空白图像。代码如下
<!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>
我被困在这里一段时间,所以任何帮助都表示赞赏。提前谢谢!
答案 0 :(得分:0)
您可能需要等到绘制图像后再调用toDataURL。火球仅在加载图像后绘制,但是在注册onload事件处理程序之后(但在它实际加载之前)立即调用rotate(以及之后的所有内容)。