2017-09-04 46 views
2

我想在黑色画布上“画”一个矩形,但它不起作用。这是我的代码:Javascript | HTML画布错误

window.onload = function() { 
 
    canvas = document.getElementById('canvas'); 
 
    canvasContext = canvas.getContext('2d'); 
 

 
    draw(); 
 
} 
 

 
function draw() { 
 
    canvasContext.fillstyle='black'; 
 
    canvasContext.fillRect(0,0,800,600); 
 
    canvasContext.fillstyle='white'; 
 
    canvasContext.fillRect(0,0,10,10); 
 
}
<canvas id="canvas" width="800" height="600"></canvas>

为什么它不工作?

+1

^h你好 - 什么不具体?它显示任何东西吗? –

+1

它不是**问题,但是:该代码正在成为[隐性全局的恐怖]的猎物(http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html) *(这是我贫血的小博客上的一篇文章)*。在适当的范围声明你的变量。在这种情况下,我可能会删除'onload'处理程序,而只是将所有代码放在HTML末尾的'script'范围函数中,就在关闭''标签之前。 –

+0

canvasContext将无法在绘图函数中访问 –

回答

1

您使用小写字母代替填充样式的大写的 “S”

变化

canvasContext.fillstyle 

“S”
canvasContext.fillStyle 

window.onload = function() { 
 
    canvas = document.getElementById('canvas'); 
 
    canvasContext = canvas.getContext('2d'); 
 

 

 
    draw(); 
 

 
} 
 

 
function draw() { 
 
    canvasContext.fillStyle='black'; 
 
    canvasContext.fillRect(0,0,800,600); 
 
    canvasContext.fillStyle='white'; 
 
    canvasContext.fillRect(0,0,100,100); 
 

 

 
}
<canvas id="canvas" width="800" height="600"></canvas>

+0

代码转储不是*有用的*答案。说*你改变了什么,以及*为什么*。 –

+1

但是,拼写错误不需要答案,只是评论和(如果可以的话)关闭投票。发布答案可以防止OP删除问题,这是正确的行动方式,因为这对未来其他人没有用(并且可能会迫使他们接受downvotes的rep损失)。 –

+0

K我已编辑我的答案 –