2011-05-29 162 views
1

我在討論html5和javascript(我對這兩者都一無所知)。我找到了一些html5的例子,將其複製並開始試驗。這裏有一些代碼。想法是,當任何按鍵被按下時,兩個方格開始向左移動(不在其後面清理)。我不明白的是爲什麼我不能改變顏色(我在下面指出)。有任何想法嗎?我顯然做了一件非常錯誤的事。html5 javascript fillstyle does not work

<!doctype html> 

<!-- this source copied from http://www.xanthir.com/blog/b48B0 --> 

<canvas width=800 height=800> 
</canvas> 

<script> 


var canvas = document.getElementsByTagName("canvas")[0]; 
var context = canvas.getContext('2d'); 

var x = 230; 
var y = 380; 

// First, we'll paint the whole canvas black. 
context.fillStyle = "black"; 
context.fillRect(0,0,800,800); 

context.fillStyle = "red"; 
context.fillRect(0,0,30,30); 

context.fillRect(0,100,30,30); 

context.fillStyle = "green"; 
context.fillRect(0,200,30,30); 


// Now we'll draw some shapes 
// circle 
context.fillStyle = "#06c"; 
context.strokeStyle = "white"; 
// These can be any CSS color. 
context.lineWidth = 3; 
context.beginPath(); 
context.moveTo(450,250); 
context.arc(375,250,75,0,2*Math.PI,false) 
context.closePath(); 
context.fill(); 
context.stroke(); 

// A triangle! And a rainbow! 
context.beginPath(); 
context.moveTo(150,50); 
context.lineTo(90,150); 
context.lineTo(210,150); 
context.lineTo(150,50); 
context.closePath(); 
var rainbow = context.createLinearGradient(150,50,150,150); 
rainbow.addColorStop(.1,"red"); 
rainbow.addColorStop(.3,"orange"); 
rainbow.addColorStop(.5,"yellow"); 
rainbow.addColorStop(.7,"lime"); 
rainbow.addColorStop(.9,"blue"); 
context.fillStyle = rainbow; 
context.fill(); 

// Some text! And a shadow! 
context.shadowOffsetX = -2; 
context.shadowOffsetY = 2; 
context.shadowColor = "#f88"; 
context.shadowBlur = .01; 
context.fillStyle = "red"; 
context.font = "bold 72px monospace"; 
context.fillText("Foo Bar",30,400); 

context.fillStyle = "blue";  
context.fillRect(0,300,30,30); 

// ???????????? end of main. The current context now seems to remain (blue fillstyle with some shadow) 


// routine here : press any key to animate two new blocks over writing ---------------- 

document.onkeydown = function(e) { 

context.fillstyle = "red";  // <-- ???????? this doesnt work (remains same colour as last one in main) 
context.fillRect(x,y,50,50);  // <-- ???????? draws a square in blue, not red 

x = x - 5; 

context.fillstyle = "white";  // <-- ???????? this doesnt work (remains same colour as last one in main) 
context.fillRect(x -100,y ,50,50); // <-- ???????? draws a square in blue, not white 


} 

+3

它是'context.fillStyle',大寫'S'。 – 2011-05-29 11:41:13

回答

2

因爲你寫fillstyle而不是fillStyle。您需要大寫S.

它在JavaScript中有效,因爲您只是將新的fillstyle字段(該字段不存在且無意義)附加到該上下文。

所以你一定要小心。錯別字可能會導致很多麻煩,因爲結果代碼在技術上不是錯誤,但它肯定不是您想要的!

+0

是的,就是這樣。我甚至一遍又一遍地檢查了它,我仍然看不到它!感謝隊友,你搖滾。 – 2011-05-29 19:30:25