Html5 canvas和javascript document.getElementById()返回null [英] Html5 canvas and javascript document.getElementById() returns null
本文介绍了Html5 canvas和javascript document.getElementById()返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用html5画布,当我这样做时
I'm trying to use html5 canvas and when I do
var c=document.getElementById('myCanvas');
var ctx=c.getContext('2d');
ctx.fillStyle="#FF0000";
ctx.fillRect(0,0,150,75);
这里是html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="game.js"></script>
</head>
<body>
<canvas id="myCanvas" width="512" height="480" style="border:1px solid #000000;">
</canvas>
</body>
</html>
我不知道出了什么问题
推荐答案
在DOM准备就绪并加载窗口之前,您的脚本可能会运行,例如:
Chances are your script is run before your DOM is ready and window has loaded, try for instance:
window.onLoad=function(){
var c=document.getElementById('myCanvas');
var ctx=c.getContext('2d');
ctx.fillStyle="#FF0000";
ctx.fillRect(0,0,150,75);
};
这篇关于Html5 canvas和javascript document.getElementById()返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文