2012-12-03 40 views
1

我想創建一個使用外部JavaScript文件的JavaScript畫布。但由於某種原因,當我運行我的代碼而不是獲得我已編碼的畫布時,我只是得到一個白色塊。鉻調試器發現我的代碼沒有問題,所以我失去了任何幫助將大大appriciated。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(); 
} 

回答

0

事件類型需要編寫小寫:load,即

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

名單例如,Mozilla引用了available event types

只是一個提示:您可以通過Chrome調試您的onLoad功能設置斷點,以確保它是由你的事件偵聽器調用。這不是,這讓我注意到你的addEventListener方法調用。

+0

謝謝,我看着那幾個小時,現在沒有運氣,覺得有點愚蠢。 –

0

這是很重要的,如果實現的東西不起作用:

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

在window.onload,「負荷」
使用小寫字母,並且不加「的」,以開始