我得到了“;未捕获的类型错误:无法读取属性'宽度'“为空”;在遵循教程之后

I am getting "Uncaught TypeError: Cannot read property 'width' of null" after following a tutorial

本文关键字:为空 宽度 属性 之后 教程 读取 错误 类型      更新时间:2023-09-26

这是我的javascript代码,但我似乎也没有什么问题。我的html id也没有错。我在youtube上学习了一个教程,它对做这件事的人有效。有人能帮我吗?

var canvas;
var ctx;
var background;
var width = 300;
var height = 200;
var cloud;
var cloud_x;
function init() {
    canvas = document.getElementById("mycanvas");
    width = canvas.width; //THIS IS WHERE I GET MY ERROR
    height = canvas.height;
    ctx = canvas.getContext("2d");
    // init background 
    background = new Image();
    background.src = 'http://silveiraneto.net/wp-content/uploads/2011/06/forest.png';
    // init cloud
    cloud = new Image();
    cloud.src = 'http://silveiraneto.net/wp-content/uploads/2011/06/cloud.png';
    cloud.onload = function(){
        cloud_x = -cloud.width;
    };
    return setInterval(main_loop, 10);
}
function update(){
    cloud_x += 0.3;
    if (cloud_x > width ) {
        cloud_x = -cloud.width;
    }
}
function draw() {
    ctx.drawImage(background,0,0);
    ctx.drawImage(cloud, cloud_x, 0);
}
function main_loop() {
    draw();
    update();
}
init();

我的html

<canvas id="mycanvas" width="640" height="480">Alternative text if browser don't support canvas.</canvas>

更改此行:

init();

通过这条线:

document.addEventListener('DOMContentLoaded', init, false);

DOM准备就绪时,将调用init函数。

jsfiddle