triangle.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. function Triangle() {
  2. var x = 10, y = 10, base = 5;
  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 + base > canvas.width) {
  14. x = canvas.width - base;
  15. velocity.x *= -1.1;
  16. }
  17. if(x - base < 0) {
  18. x = base;
  19. velocity.x *= -1.1;
  20. }
  21. if(y + base * 2 > canvas.height) {
  22. y = canvas.height - (base * 2);
  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.moveTo(x, y);
  36. context.lineTo(x - base, y + base * 2);
  37. context.lineTo(x + base, y + base * 2);
  38. context.lineTo(x, y);
  39. context.stroke();
  40. }
  41. }