Canvas中 drawImage绘制图片不显示

时间:2023-12-29 14:59:08

在学习 html5中的 Canvas.drawImage时写了如下代码:

<!doctype html>
<html>
<head><title>研究</title></head>
<body>
<canvas id="canvas" style="width:500px;height:400px; border:1px solid red"></canvas>
<img id="img" src="ggg.jpg" hidden />
</body>
<Script type="text/javascript">
var cxt = document.getElementById("canvas").getContext("2d");
var imgElement = document.getElementById("img");
cxt.drawImage(imgElement, 10, 10, 200, 200);
</Script>
</html>

在charome和firefox中都无法显示绘制的图片效果。后来查询了很多资料,才知道canvas在绘制图片的时候要等到img的图片完全加载到客户端后才可以绘制正确,现在的代码中直接是绘制图片,图片还没加载完就开始在绘制图片了,把代码稍微改下:

  

<!doctype html>
<html>
<head><title>研究</title></head>
<body>
<canvas id="canvas" style="width:500px;height:400px; border:1px solid red"></canvas>
<img id="img" src="ggg.jpg" hidden />
</body>
<Script type="text/javascript">
var cxt = document.getElementById("canvas").getContext("2d");
var imgElement = document.getElementById("img");
setTimeout(function () { cxt.drawImage(imgElement, 10, 10, 200, 200); },0);
</Script>
</html>

  或者

<!doctype html>
<html>
<head><title>研究</title></head>
<body>
<canvas id="canvas" style="width:500px;height:400px; border:1px solid red"></canvas>
<img id="img" src="ggg.jpg" hidden />
</body>
<Script type="text/javascript">
var cxt = document.getElementById("canvas").getContext("2d");
var imgElement = document.getElementById("img");
imgElement.onload = function () { cxt.drawImage(imgElement, 10, 10, 200, 200); };
</Script>
</html>

  就可以正常显示绘制的图片了。