難道你們參考老師的代碼,瀏覽器不會報錯嗎?
<!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 里面來,但無濟于事。
請大神教我如何解決
2017-12-22
<!DOCTYPE?html> <html> ??<head> ????<meta?charset="UTF-8"> ????<meta?name="viewport"?content="width=device-width,?initial-scale=1.0"> ????<meta?http-equiv="X-UA-Compatible"?content="ie=edge"> ????<title>Canvas繪圖詳解?16</title> ????<style> ??????canvas?{ ????????border:?1px?solid?#aaa; ????????display:?block; ????????margin:?50px?auto; ??????} ????</style> ??</head> ??<body> ????<canvas?id="canvas"?width="800"?height="800">不好意思,您的瀏覽器不支持canvas。</canvas> ????<script?type="text/javascript"> ??????var?balls?=?[]; ??????var?canvas?=?document.getElementById("canvas"); ??????var?ctx?=?canvas.getContext("2d"); ??????window.onload?=?function()?{ ????????for?(var?i?=?0;?i?<?10;?i++)?{ ??????????var?ball?=?{ ????????????x:?Math.random()?*?800, ????????????y:?Math.random()?*?800, ????????????r:?Math.random()?*?50?+?20 ??????????}; ??????????balls[i]?=?ball; ????????} ????????canvas.addEventListener("mousemove",?detect); ??????}; ??????function?draw(x,?y)?{ ????????for?(var?i?=?0;?i?<?balls.length;?i++)?{ ??????????ctx.beginPath(); ??????????ctx.arc(balls[i].x,?balls[i].y,?balls[i].r,?0,?Math.PI?*?2); ??????????if?(ctx.isPointInPath(x,?y))?{ ????????????ctx.fillStyle?=?"#ff0000"; ??????????}?else?{ ????????????ctx.fillStyle?=?"#058"; ??????????} ??????????ctx.fill(); ????????} ??????} ??????function?detect(e)?{ ????????var?x?=?e.clientX?-?canvas.getBoundingClientRect().left; ????????var?y?=?e.clientY?-?canvas.getBoundingClientRect().top; ????????draw(x,?y); ??????} ????</script> ??</body> </html>