box.js 988 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. function Box() {
  2. var x = 10, y = 10, width = 10, height = 10;
  3. var velocity = {x: 1, y: 1};
  4. this.init = function(canvas) {
  5. x = Math.floor(canvas.width * Math.random());
  6. y = Math.floor(canvas.height * Math.random());
  7. velocity.x = Math.floor(10 * Math.random() - 5);
  8. velocity.y = Math.floor(10 * Math.random() - 5);
  9. };
  10. this.update = function(canvas) {
  11. x += velocity.x;
  12. y += velocity.y;
  13. if(x + width > canvas.width) {
  14. x = canvas.width - width;
  15. velocity.x *= -1.1;
  16. }
  17. if(x < 0) {
  18. x = 0;
  19. velocity.x *= -1.1;
  20. }
  21. if(y + height > canvas.height) {
  22. y = canvas.height - height;
  23. velocity.y *= -1.1;
  24. }
  25. if(y < 0) {
  26. y = 0;
  27. velocity.y *= -1.1;
  28. }
  29. velocity.x = Math.max(-5, Math.min(5, velocity.x));
  30. velocity.y = Math.max(-5, Math.min(5, velocity.y));
  31. },
  32. this.draw = function(context) {
  33. context.strokeStyle = "#000000";
  34. context.beginPath();
  35. context.rect(x ,y, width, height);
  36. context.stroke();
  37. }
  38. }