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>
敬具!