这是我的JavaScript。我有一个动画功能,我认为这是重绘背景代码的地方。我试图使用document.getElementById来获取画布的id,并给出background:white的样式规则。但它没有用。所有帮助表示赞赏!:
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();
});
答案 0 :(得分:0)
以下是我注意到的一些事情:
您没有声明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()
在绘制播放器之前如何清除画布。
我创建了一个带有修复here的工作JSFiddle。