难道你们参考老师的代码,浏览器不会报错吗?
<!DOCTYPE> <html> <head> <script> var balls=[] var canvas=document.getElementById('Canvas'); var context=canvas.getContext('2d'); window.onload=function(){ canvas.width=1024; canvas.height=768; for(i=0;i<10;i++){ var aball={ x:Math.random()*canvas.width, y:Math.random()*canvas.height, R:Math.random()*50+20 } balls[i]=aball } draw() canvas.addEventListener('mousemove',detect); } function draw(x,y){ context.clearRect(0,0,canvas.width,canvas.height); for(var i=0;i<balls.length;i++){ context.beginPath(); context.arc(balls.x,balls.y,balls.R,0,2*Math.PI,false); if(context.isPointInPath(x,y)){ context.fillStyle='red' }else{ context.fillStyle='#0090D2' } context.fill() } } function detect(event){ var x=event.clientX-canvas.getBoundingClientRect().left; var y=event.clientY-canvas.getBoundingClientRect().top; draw(x,y) } </script> </head> <body> <canvas id='Canvas' style="margin:50px 400px auto;border:1px solid #ccc"></canvas> </body> </html>
我的浏览器报错了,说是 Cannot read property 'getContext' of null 应该是无法获取上下文环境,我知道报错的原因,但不知道如何去解决,我试过把
var canvas=document.getElementById('Canvas'); var context=canvas.getContext('2d');
放到window.onload 里面来,但无济于事。
请大神教我如何解决