1

外部の JavaScript ファイルを使用して JavaScript キャンバスを作成しようとしています。しかし、何らかの理由で、コーディングしたキャンバスを取得する代わりにコードを実行すると、白いブロックが表示されます。クロムデバッガーは私のコードに問題を検出しないため、助けが得られないことがわかりました。

これは私のインデックスファイルです

<!doctype html>
    <html>
        <head>
            <title>Lab1</title> <script type="text/javascript" src="javascript/canvas.js"></script>
        </head>
        <body>
            <canvas id="canvas" width="800" height="600">
                Your browser does not support the canvas tag
            </canvas>
            <p>This is a simple 'Hello World' lab tutorial using the HTML5 canvas.</p>
        </body>
    </html>

そして、これは私のjavascriptファイルです

// check to see if the browser supports 
// the addEventListener function 
if(window.addEventListener) 
{
window.addEventListener 
( 
'Load', // this is the load event 
onLoad, // this is the event handler we are going to write 
false // useCapture boolean value 
);
}

// the window load event handler 
function onLoad() 
{ 
var canvas; 
var context;

// this function will initialise our variables 
function initialise() 
{
    // Find the canvas element using its id attribute. 
    canvas = document.getElementById('canvas'); 
    // if it couldn't be found 
    if (!canvas) 
    { 
        // make a message box pop up with the error. 
        alert('Error: I cannot find the canvas element!'); 
        return; 
    }
    // check if there is a getContext function 
    if (!canvas.getContext) 
    { 
        // make a message box pop up with the error. 
        alert('Error: no canvas.getContext!'); 
        return; 
    }
    // Get the 2D canvas context. 
    context = canvas.getContext('2d'); 
    if (!context) 
    { 
        alert('Error: failed to getContext!'); 
        return; 
    }
}

    // this function will actually draw on the canvas 
    function draw() 
    { 
        // set the draw fill style colour to black 
        context.fillStyle = "#000000"; 
        // fill the canvas with black 
        context.fillRect(0,0,canvas.width,canvas.height); 
        // choose a font for our message 
        context.font = "40pt Calibri"; 
        // set the draw fill colour to white 
        context.fillStyle = "#ffffff"; 
        // draw the text at the specified position 
        context.fillText("Hello World!", 150, canvas.height); 
    }
// call the initialise and draw functions 
initialise(); 
draw(); 
}
4

4 に答える 4

0

イベント タイプは小文字で記述する必要があります: load、つまり

window.addEventListener('load', onLoad, false);

使用可能なイベント タイプのリストは、たとえば Mozilla によって参照されます。

ヒント: onLoadChrome デバッガーを使用して関数にブレークポイントを設定し、イベント リスナーによって確実に呼び出されるようにすることができます。そうではなく、addEventListenerメソッド呼び出しに注意を向けました。

于 2012-12-03T11:20:52.107 に答える
0

これは、何かが機能しない場合に認識することが重要です。

window.onload = myFunction;
window.addEventListener("load", myFunction);

window.onload、「load」
は小文字を使用し、先頭に「on」を追加しないでください

于 2015-09-27T17:21:03.560 に答える