2

刚从 JavaScript 开始,我收到错误“canvas is null”

function draw() {  

    var canvas = document.getElementById("canvas");  
    var ctx = canvas.getContext("2d"); 
    var width,height;

    width = canvas.width;
    height = canvas.height;

    ctx.fillStyle = "rgb(0,0,0)";  
    ctx.fillRect (10, 10, width, height); 
    ctx.fillStyle = "rgb(200,0,0)";  
    ctx.fillRect (posx, posy, 30, 30); 

}
var posx;
var posy;
function getMouse(e){
    posx=0;posy=0;
    var ev=(!e)?window.event:e;//Moz:IE
    if (ev.pageX){
        posx=ev.pageX;posy=ev.pageY//Mozilla or compatible
    }
    else if(ev.clientX){
        posx=ev.clientX;posy=ev.clientY//IE or compatible
    }
    else{
        return false//old browsers
    }
        document.getElementById('mydiv').firstChild.data='X='+posx+' Y='+posy;
}
setInterval(draw(),1000);

该代码基本上在鼠标位置绘制了一个框(至少这是它应该做的......)

顺便说一句,“画布”是画布的 id。谢谢!

4

1 回答 1

3

最后一行应该是:

setInterval(draw,1000);

没有括号。否则,您正在调用该函数,而不是通过它。

于 2012-07-10T16:28:27.220 回答