Chrome中canvas報Cannot call method 'getContext' of null


今天在看HTML5 的CANVAS,找了一段簡單的代碼,敲好後,用CHROME打開,竟然報出Cannot call method 'getContext' of null 這個錯誤,就是說getContext這個方法沒有,唉?我就納悶啦,按理說chrome對html5支持的很好啊,應該不會有這種錯誤啊,查了些資料也沒找到,代碼如下

<html>
<head>
<script type="text/javascript"> 
	var canvas=document.getElementById("screen");
	var ctx=canvas.getContext("2d");
	ctx.fillStyle="#f00";
	ctx.fillRect(30,40,80,100);
	
</script>  
</head>
<body οnlοad="onReady()">
<canvas id="screen" width="600" height="400"> 
</canvas> 
</body>
</html>
 
後來,我想了很久,覺得是不是因爲js先於頁面載入,還沒有canvas屬性啊,於是改改看

<html>
<head>
<script type="text/javascript"> 
function onReady(){
	var canvas=document.getElementById("screen");
	var ctx=canvas.getContext("2d");
	ctx.fillStyle="#f00";
	ctx.fillRect(30,40,80,100);
	}
</script>  
</head>
<body οnlοad="onReady()">
<canvas id="screen" width="600" height="400"> 
</canvas> 
</body>
</html>

看來就是這個問題,要在頁面載入後才能獲得canvas對象,這個問題在firefox不會出現,看來是做了優化,反正還是注意吧,小問題


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章