我第一次尝试使用Canvas创建游戏。我已经显示了一张图片,但是fillStyle方法似乎不起作用(至少在Google Chrome中画布背景仍然是白色的)。
请注意,在我的代码中,canvas变量实际上是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>
.fillRect()
方法是画布的2D上下文的方法,而不是画布本身,这个答案中可能(无意中)提到了它! - Tim S.