2012-08-25 27 views
3

只是爲了創建遊戲而第一次爲canvas創作。我有一個圖像顯示,但奇怪的fillStyle方法似乎並沒有工作。 (至少畫布背景在Google Chrome中仍然是白色的。)html5 canvas上下文.fillStyle不能正常工作

請注意,在我的代碼中,canvas var實際上是canvas元素2d的上下文,也許這就是我陷入困境的地方?我看不到問題,如果其他人能夠,我會感激。

LD24.js:

const FPS = 30; 
var canvasWidth = 0; 
var canvasHeight = 0; 
var xPos = 0; 
var yPos = 0; 
var smiley = new Image(); 
smiley.src = "http://javascript-tutorials.googlecode.com/files/jsplatformer1-smiley.jpg"; 

var canvas = null; 
window.onload = init; //set init function to be called onload 

function init(){ 
    canvasWidth = document.getElementById('canvas').width; 
    canvasHeight = document.getElementById('canvas').height; 
    canvas = document.getElementById('canvas').getContext('2d'); 
    setInterval(function(){ 
     update(); 
     draw(); 
    }, 1000/FPS); 
} 

function update(){ 

} 
function draw() 
{ 
    canvas.clearRect(0,0,canvasWidth,canvasHeight); 
    canvas.fillStyle = "#FFAA33"; //orange fill 
    canvas.drawImage(smiley, xPos, yPos); 

} 

LD24.html:

<html> 
    <head> 
     <script language="javascript" type="text/javascript" src="LD24.js"></script> 
    </head> 
    <body> 



<canvas id="canvas" width="800" height="600"> 
    <p> Your browser does not support the canvas element needed to play this game :(</p> 
</canvas> 

    </body> 
</html> 

回答

3

3注:

  1. fillStyle不會引起你的畫布,以填補。這意味着當你填充 a 形狀它將填充該顏色。因此您需要編寫canvas.fillRect(xPos, yPos, width, height)

  2. 等到圖像實際加載完成,否則渲染可能不一致或出現問題。

  3. 小心在畫布中使用的跨域圖像 - 大多數瀏覽器都會拋出安全異常並停止執行代碼。

+0

衛生署不敢相信我錯過了謝謝!我如何檢查圖像已加載?是的,我一定會盡快使用自己的形象。 – Holly

+0

請注意''.fillRect()'方法是畫布'2D上下文的方法,而不是畫布本身(可能是偶然)在這個答案中提到! –

+0

@TimS。我只是按照問題中的變量名稱。我明白這可能會令人困惑。 –

1

等到圖像加載,以及:

var img = new Image(); 
img.onload = function() { 
    handleLoadedTexture(img); 
}; 
img.src = "image.png"; 

function handleLoadedTexture(img) { 
    //call loop etc that uses image 
};