I'm working on a platform game via poo.
I heard is more efficient to clear just the object you're drawing instead of clearing the whole canvas. So I'm working on this, and all goes well when the player's velocity player.Xvel
has an integer value.
But when I use a floating point value for the velocity, then my object leaves a banded trail behind it, like a barcode of stripes and gaps.
Can you help me identify what's causing this artifact?
var canvas = {};
canvas.obj = document.getElementById('canvas');
canvas.ctx = canvas.obj.getContext('2d');
canvas.width = canvas.obj.width;
canvas.height = canvas.obj.height;
var Object = function() {
this.draw = function() {
switch (this.fill) {
case true:
canvas.ctx.fillStyle = this.color;
canvas.ctx.fillRect(this.x, this.y, this.width, this.height);
break;
case false:
canvas.ctx.strokeStyle = this.color;
canvas.ctx.strokeRect(this.x, this.y, this.width, this.height);
break;
default:
console.log('draw err');
}
};
this.clear = function() {
var prevCoords = {};
prevCoords.x = this.x - this.xVel;
prevCoords.y = this.y - this.yVel;
// lineWidth:fix
canvas.ctx.clearRect(prevCoords.x, prevCoords.y, this.width, this.height);
};
};
var player = new Object();
var game = {};
player.width = 10;
player.height = 50;
player.x = 200;
player.y = 150;
player.xVel = 0.9; // try to change this to integer/float value then run
player.yVel = 0;
player.color = 'white';
player.fill = true;
player.movement = function() {
this.x += this.xVel;
this.y += this.yVel;
};
game.key = [];
game.fps = 15;
game.obj = setInterval(function() {
player.clear();
player.draw();
player.movement();
}, 1000 / game.fps);
body {
background: rgb(110, 110, 110);
color: rgb(230, 230, 230);
}
canvas {
background: rgb(60, 60, 60);
}
<canvas id="canvas" width="460" height="360"></canvas>
<form action="">
<label>Game:</label>
<input type="button" value="run" onclick="" />
<input type="button" value="stop" onclick="clearInterval(game.obj);console.log('end');" />
</form>