I am animating a rectangle through a canvas element using js. I want to change the direction of the animation when the rectangle reaches the width of the canvas, but cannot work out the logic when it rotates once, but then goes right again, essentially sticking it to the width of the canvas.
Please check out the code below for a clearer picture:
function startGame() {
game.start();
game.createSquare('red', 100, 10, 10, 10);
}
function updateGame() {
game.clear();
if(game.x < game.canvas.width){
game.x++;
} else {
game.x--;
}
game.update();
}
var game = {
canvas: document.createElement('canvas'),
start: function () {
this.context = this.canvas.getContext('2d');
this.canvas.height = 400;
this.canvas.width = 400;
document.body.insertBefore(this.canvas ,document.body.childNodes[0]);
},
clear: function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
createSquare: function(color, height, width, x, y) {
this.height = height;
this.width = width;
this.color = color;
this.x = x;
this.y = y;
this.update = function(){
this.context.fillStyle = this.color;
this.context.fillRect(this.x , this.y , this.width, this.height);
}
}
}
startGame();
setInterval(updateGame,50);
user6002037
source
share