我使用 jQuery 的 $(document).ready 函数。看来我不能直接用它调用函数。我不知道为什么。当我尝试使用 getElementById 查找画布时出现错误。
这有效:
<!DOCTYPE html>
<html>
<head>
<script language="javascript" src="http://code.jquery.com/jquery-1.4.2.js" ></script>
<script type="text/javascript">
var test="this is a test";
var canvas;
var ctx;
$(document).ready( function(){
init();
});
function init() {
console.log (test);
canvas=document.getElementById('canvas');
ctx = canvas.getContext('2d');
}
</script>
</head>
<body>
<div>
<canvas id="canvas" width="300" height="300">
No HTML5 support.
</canvas>
</div>
</body>
</html>
这也有效:
<!DOCTYPE html>
<html>
<head>
<script language="javascript" src="http://code.jquery.com/jquery-1.4.2.js" ></script>
<script type="text/javascript">
var test="this is a test";
var canvas;
var ctx;
$(document).ready(function(){
console.log (test);
canvas=document.getElementById('canvas');
ctx = canvas.getContext('2d');
});
</script>
</head>
<body>
<div>
<canvas id="canvas" width="300" height="300">
No HTML5 support.
</canvas>
</div>
</body>
</html>
但这给出了一个错误......
<!DOCTYPE html>
<html>
<head>
<script language="javascript" src="http://code.jquery.com/jquery-1.4.2.js" ></script>
<script type="text/javascript">
var test="this is a test";
var canvas;
var ctx;
$(document).ready(init());
function init() {
console.log (test);
canvas=document.getElementById('canvas'); // <= Error here!
ctx = canvas.getContext('2d');
}
</script>
</head>
<body>
<div>
<canvas id="canvas" width="300" height="300">
No HTML5 support.
</canvas>
</div>
</body>
</html>
亲切的问候!