すみません、今回は書き方についてお聞きしたいのですが
MDNと言うサイトでアニメーションを学んで遊ぼうとしたところ、
Oreillyのサンプルと違ってダイレクトにscript内に描写要素が書かれていて
Oreillyではscriptはheadに書くものだと書かれていたのにbodyに書かれています
そのコードでscriptをheadに入れてしまうと
sample.html:9 Uncaught TypeError: Cannot read property 'getContext' of null
at sample.html:9
と出て来てしまい読み込んでくれないです。
自分としてはMDNの書き方の方がかなり見やすく感じるのですが、
windowLoadのイベント無しでbodyにfunctionも無しでscript直打ちしちゃって大丈夫なんでしょうか??
MDNのサイトのコードです
javascript
1<!DOCTYPE html> 2<html> 3<head> 4 <meta charset="utf-8" /> 5 <title>Sample of MDN</title> 6 <style>* { padding: 0; margin: 0; } 7 canvas { background: #eee; display: 8 block; margin: 0 auto; } 9 </style> 10</head> 11<body> 12 13<canvas id="myCanvas" width="480" height="320"></canvas> 14 15<script> 16 var canvas = document.getElementById("myCanvas"); 17 var ctx = canvas.getContext("2d"); 18 ctx.beginPath(); 19 ctx.rect(20, 40, 50, 50); 20 ctx.fillStyle = "#FF0000"; 21 ctx.fill(); 22 ctx.closePath(); 23 ctx.beginPath(); 24 ctx.arc(240, 160, 20, 0, Math.PI*2, false); 25 ctx.fillStyle = "green"; 26 ctx.fill(); 27 ctx.closePath(); 28 ctx.beginPath(); 29 ctx.rect(160, 10, 100, 40); 30 ctx.strokeStyle = "rgba(0, 0, 255, 0.5)"; 31 ctx.stroke(); 32 ctx.closePath(); 33</script> 34 35</body> 36</html> 37
Oreillyを参考にしたwindowLoadを使う書き方です
javascript
1<!DOCTYPE html> 2<html lang="en"> 3<head> 4 <meta charset="UTF-8"> 5 6 <title>EX2 seriesMDN</title> 7 8 <style>* { padding: 0; margin: 0; } 9 canvas { background: #eee; display: 10 block; margin: 0 auto; } 11 </style> 12 13 <script > 14 window.addEventListener('load', eventWindowLoaded, false); 15 16 function eventWindowLoaded() { 17 canvasApp(); 18 } 19 function canvasApp() { 20 var theCanvas = document.getElementById("canvas"); 21 var ctx = theCanvas.getContext("2d"); 22 drawScreen(); 23 function drawScreen() { 24 ctx.beginPath(); 25 ctx.rect(20, 40, 50, 50); 26 ctx.fillStyle = "#FF0000"; 27 ctx.fill(); 28 ctx.closePath(); 29 30 ctx.beginPath(); 31 ctx.arc(240, 160, 20, 0, Math.PI*2, false); 32 ctx.fillStyle = "green"; 33 ctx.fill(); 34 ctx.closePath(); 35 36 ctx.beginPath(); 37 ctx.rect(160, 10, 100, 40); 38 ctx.strokeStyle = "rgba(0, 0, 255, 0.5)"; 39 ctx.stroke(); 40 ctx.closePath(); 41 42 } 43 } 44 45 46 47 </script> 48</head> 49<body> 50 <canvas id="canvas" width="480" height="320">No canvas sup</canvas> 51</body> 52</html>
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/09/12 07:29