Arrow.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. var Arrow = function(tadpole, camera) {
  2. var arrow = this;
  3. this.x = 0;
  4. this.y = 0;
  5. this.tadpole = tadpole;
  6. this.camera = camera;
  7. this.angle = 0;
  8. this.distance = 10;
  9. this.opacity = 1;
  10. this.update = function() {
  11. arrow.angle = Math.atan2(tadpole.y - arrow.camera.y, tadpole.x - arrow.camera.x);
  12. };
  13. this.draw = function(context, canvas) {
  14. var cameraBounds = arrow.camera.getBounds();
  15. if( arrow.tadpole.x < cameraBounds[0].x ||
  16. arrow.tadpole.y < cameraBounds[0].y ||
  17. arrow.tadpole.x > cameraBounds[1].x ||
  18. arrow.tadpole.y > cameraBounds[1].y ) {
  19. var size = 4;
  20. var arrowDistance = 100;
  21. var angle = arrow.angle;
  22. var w = (canvas.width/2) - 10;
  23. var h = (canvas.height/2) - 10;
  24. var aa = Math.atan(h / w);
  25. var ss = Math.cos(angle);
  26. var cc = Math.sin(angle);
  27. if((Math.abs(angle) + aa) % Math.PI / 2 < aa) {
  28. arrowDistance = w / Math.abs(ss);
  29. } else {
  30. arrowDistance = h / Math.abs(cc);
  31. }
  32. var x = (canvas.width/2) + Math.cos(arrow.angle) * arrowDistance;
  33. var y = (canvas.height/2) + Math.sin(arrow.angle) * arrowDistance;
  34. var point = calcPoint(x, y, this.angle, 2, size);
  35. var side1 = calcPoint(x, y, this.angle, 1.5, size);
  36. var side2 = calcPoint(x, y, this.angle, 0.5, size);
  37. // Draw arrow
  38. context.fillStyle = 'rgba(255,255,255,'+arrow.opacity+')';
  39. context.beginPath();
  40. context.moveTo(point.x, point.y);
  41. context.lineTo(side1.x, side1.y);
  42. context.lineTo(side2.x, side2.y)
  43. context.closePath();
  44. context.fill();
  45. }
  46. };
  47. var calcPoint = function(x, y, angle, angleMultiplier, length) {
  48. return {
  49. x: x + Math.cos(angle + Math.PI * angleMultiplier) * length,
  50. y: y + Math.sin(angle + Math.PI * angleMultiplier) * length
  51. }
  52. };
  53. }