QuadraticCurve.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import {Object2D} from "../Object2D.js";
  2. import {Vector2} from "../math/Vector2.js";
  3. import {Circle} from "./Circle.js";
  4. import {Line} from "./Line.js";
  5. /**
  6. * Bezier curve object draw as bezier curve between two points.
  7. *
  8. * @class
  9. * @extends {Object2D}
  10. */
  11. function QuadraticCurve()
  12. {
  13. Line.call(this);
  14. /**
  15. * Control point of the quadratic curve used to control the curvature of the line between the from and to point.
  16. *
  17. * The curve is interpolated in the direction of the control point it defined the path of the curve.
  18. *
  19. * @type {Vector2}
  20. */
  21. this.controlPoint = new Vector2();
  22. }
  23. QuadraticCurve.prototype = Object.create(Line.prototype);
  24. QuadraticCurve.prototype.constructor = QuadraticCurve;
  25. QuadraticCurve.prototype.type = "QuadraticCurve";
  26. /**
  27. * Create a quadratic curve helper, to edit the curve control point.
  28. *
  29. * Helper objects are added to the parent of the curve object.
  30. *
  31. * @static
  32. * @param {QuadraticCurve} object Object to create the helper for.
  33. */
  34. QuadraticCurve.curveHelper = function(object)
  35. {
  36. var fromLine = new Line();
  37. fromLine.from = object.from;
  38. fromLine.to = object.controlPoint;
  39. object.parent.add(fromLine);
  40. var controlPoint = new Circle();
  41. controlPoint.radius = 3;
  42. controlPoint.layer = object.layer + 1;
  43. controlPoint.draggable = true;
  44. controlPoint.position = object.controlPoint;
  45. controlPoint.onPointerDrag = function(pointer, viewport, delta)
  46. {
  47. Object2D.prototype.onPointerDrag.call(this, pointer, viewport, delta);
  48. object.controlPoint.copy(controlPoint.position);
  49. };
  50. object.parent.add(controlPoint);
  51. var toLine = new Line();
  52. toLine.from = object.to;
  53. toLine.to = object.controlPoint;
  54. object.parent.add(toLine);
  55. };
  56. QuadraticCurve.prototype.draw = function(context, viewport, canvas)
  57. {
  58. context.beginPath();
  59. context.moveTo(this.from.x, this.from.y);
  60. context.quadraticCurveTo(this.controlPoint.x, this.controlPoint.y, this.to.x, this.to.y);
  61. context.stroke();
  62. };
  63. QuadraticCurve.prototype.serialize = function(recursive)
  64. {
  65. var data = Line.prototype.serialize.call(this, recursive);
  66. data.controlPoint = this.controlPoint.toArray();
  67. return data;
  68. };
  69. QuadraticCurve.prototype.parse = function(data)
  70. {
  71. Line.prototype.parse.call(this, data);
  72. this.controlPoint.fromArray(data.controlPoint);
  73. };
  74. export {QuadraticCurve};