1

我正在尝试使用外部 javascript 文件创建 javascript 画布。但是由于某种原因,当我运行我的代码而不是获取我编码的画布时,我只得到一个白色块。chrome 调试器发现我的代码没有问题,所以我迷路了,任何帮助都会得到很大的帮助。

这是我的索引文件

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

1
window.onload = function(){
    // put here your JS code
}
于 2019-08-06T18:18:24.583 回答
0

事件类型需要小写:load,即

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

例如,Mozilla 引用了可用事件类型的列表。

提示:您可以onLoad使用 Chrome 调试器在函数中设置断点,以确保事件侦听器调用它。事实并非如此,这让我注意到了你的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 回答
0
window.onload = function(){
  // here goes your code
}
于 2019-11-17T08:06:47.913 回答