html5 drawImage 不显示问题

html5在使用drawImage绘图的时候,出现刷新就不显示的问题,原来要想是图片正常显示需要为图片添加一个onload事件,直接看代码

<!DOCTYPE HTML>
<html>
    <head>
        <meta content="text/html" charset="utf8">
    </head>
<body>


<canvas id="myCanvas4" width="200" height="100" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>

<script type="text/javascript">

var c=document.getElementById("myCanvas4");
var cxt=c.getContext("2d");
var img=new Image();
img.src="./images/50ab2f61403bf44f.png";
img.onload=function(){
    cxt.drawImage(img,0,0);    
};
cxt.drawImage(img,0,0);
</script>
</body>
</html>


代码技巧