这是我的 JavaScript。我有一个动画函数,我认为这是重绘背景代码的地方。我尝试使用 document.getElementById 来获取画布的 id,并给出背景的样式规则:白色。但这没有用。感谢所有帮助!:
function initCanvas(){
var ctx = document.getElementById('my_canvas').getContext('2d');
var cW = ctx.canvas.width, cH = ctx.canvas.height;
var dist = 10;
function Player(){
this.x = 0, this.y = 0, this.w = 50, this.h = 50;
ctx.fillStyle = "orange";
this.render = function(){
ctx.fillRect(this.x, this.y, this.w, this.h);
}
}
var player = new Player();
player.x = 100;
player.y = 225;
function animate(){
//This is where I think the background redrawing should go
player.render();
}
var animateInterval = setInterval(animate, 30);
document.addEventListener('keydown', function(event) {
var key_press = String.fromCharCode(event.keyCode);
if(key_press == "W"){
player.y-=dist;
} else if(key_press == "S"){
player.y+=dist;
} else if(key_press == "A"){
player.x-=dist;
} else if(key_press == "D"){
player.x+=dist;
}
});
}
window.addEventListener('load', function(event) {
initCanvas();
});
以下是我注意到的几件事:
你没有声明
var canvas = document.getElementById('my_canvas');
你的
initCanvas()
没有发射(这不是为了我)
您的
render()
函数应在绘制角色之前重置 fillStyle
。在初始化 fillStyle
构造函数时设置 Player
是没有用的(它可以被覆盖)。
您的
animate()
函数应如下所示:
function animate(){
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, canvas.width, canvas.height);
player.render();
}
注意
fillRect()
在绘制播放器之前如何清除画布。
我已经创建了一个工作 JSFiddle 并修复了here。