function Box() { var x = 10, y = 10, width = 10, height = 10; var velocity = {x: 1, y: 1}; this.init = function(canvas) { x = Math.floor(canvas.width * Math.random()); y = Math.floor(canvas.height * Math.random()); velocity.x = Math.floor(10 * Math.random() - 5); velocity.y = Math.floor(10 * Math.random() - 5); }; this.update = function(canvas) { x += velocity.x; y += velocity.y; if(x + width > canvas.width) { x = canvas.width - width; velocity.x *= -1.1; } if(x < 0) { x = 0; velocity.x *= -1.1; } if(y + height > canvas.height) { y = canvas.height - height; velocity.y *= -1.1; } if(y < 0) { y = 0; velocity.y *= -1.1; } velocity.x = Math.max(-5, Math.min(5, velocity.x)); velocity.y = Math.max(-5, Math.min(5, velocity.y)); }, this.draw = function(context) { context.strokeStyle = "#000000"; context.beginPath(); context.rect(x ,y, width, height); context.stroke(); } }