var game = {
sprites: {
battleship: undefined,
enemyShip: undefined
},
init: function() {
var canvas = document.getElementById('myCanvas');
this.ctx = canvas.getContext("2d");
window.addEventListener('keydown', (event) => {
if (event.keyCode == 37) {
game.battleship.x -= 8
} else if (event.keyCode == 39) {
game.battleship.x += 8
}
this.ctx.clearRect(0, 0, this.width, this.height);
})
},
load: function() {
for (var key in this.sprites) {
this.sprites[key] = new Image();
this.sprites[key].src = "sprites/" + key + ".png";
}
},
start: function() {
this.init();
this.load();
this.run();
},
render: function() {
this.ctx.clearRect(0, 0, this.width, this.height);
this.ctx.drawImage(this.sprites.battleship, this.battleship.x, this.battleship.y, 68, 68);
this.ctx.drawImage(this.sprites.enemyShip, this.enemyShip.x, this.enemyShip.y, 60, 60);
},
run: function() {
this.render();
window.requestAnimationFrame(() => {
game.run();
});
this.ctx.clearRect(0, 0, this.width, this.height);
}
};
game.battleship = {
x: 355,
y: 520
}
game.enemyShip = {
x: 355,
y: -10,
grav: 1
}
window.addEventListener('load', () => {
game.start()
});
-
а зачем делать clearRect и до и после render?– Grundy ♦20 сен 2020 в 22:20
Добавить комментарий
|
1 ответ
Объект оставлял след из-за того, что this.width
и this.height
не выставлены.
Соответственно при this.ctx.clearRect(0, 0, this.width, this.height);
чистится область 0px
на 0px
var game = {
width: 0,
height: 0,
sprites: {
battleship: undefined,
enemyShip: undefined
},
init: function() {
var canvas = document.getElementById('myCanvas');
this.ctx = canvas.getContext("2d");
// Т.к. при очистке полотна идёт обращение к this.width и this.height
// их нужно выставить равными размеру полотна которое мы чистим
this.width = canvas.width;
this.height = canvas.height;
window.addEventListener('keydown', (event) => {
if (event.keyCode == 37) {
game.battleship.x -= 8
} else if (event.keyCode == 39) {
game.battleship.x += 8
}
})
},
load: function() {
for (var key in this.sprites) {
this.sprites[key] = new Image();
this.sprites[key].src =
`https://via.placeholder.com/50x50.png?text=${key}`
//"sprites/" + key + ".png";
}
},
start: function() {
this.init();
this.load();
this.run();
},
render: function() {
this.ctx.clearRect(0, 0, this.width, this.height);
this.ctx.drawImage(this.sprites.battleship, this.battleship.x, this.battleship.y, 68, 68);
this.ctx.drawImage(this.sprites.enemyShip, this.enemyShip.x, this.enemyShip.y, 60, 60);
},
run: function() {
this.render();
window.requestAnimationFrame(() => {
game.run();
// Зачем чистить экран сразу после того как отрисовали?
//this.ctx.clearRect(0, 0, this.width, this.height);
});
}
};
game.battleship = {
x: 10,
y: 10
}
game.enemyShip = {
x: 355,
y: -10,
grav: 1
}
window.addEventListener('load', () => {
game.start()
});
canvas{
border:1px solid black;
}
<canvas id="myCanvas"></canvas>