QuadraticCurve.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. Object2D.register(QuadraticCurve, "QuadraticCurve");
  27. /**
  28. * Create a quadratic curve helper, to edit the curve control point.
  29. *
  30. * Helper objects are added to the parent of the curve object.
  31. *
  32. * @static
  33. * @param {QuadraticCurve} object Object to create the helper for.
  34. */
  35. QuadraticCurve.curveHelper = function(object)
  36. {
  37. var fromLine = new Line();
  38. fromLine.from = object.from;
  39. fromLine.to = object.controlPoint;
  40. object.parent.add(fromLine);
  41. var controlPoint = new Circle();
  42. controlPoint.radius = 3;
  43. controlPoint.layer = object.layer + 1;
  44. controlPoint.draggable = true;
  45. controlPoint.position = object.controlPoint;
  46. controlPoint.onPointerDrag = function(pointer, viewport, delta)
  47. {
  48. Object2D.prototype.onPointerDrag.call(this, pointer, viewport, delta);
  49. object.controlPoint.copy(controlPoint.position);
  50. };
  51. object.parent.add(controlPoint);
  52. var toLine = new Line();
  53. toLine.from = object.to;
  54. toLine.to = object.controlPoint;
  55. object.parent.add(toLine);
  56. };
  57. QuadraticCurve.prototype.draw = function(context, viewport, canvas)
  58. {
  59. context.beginPath();
  60. context.moveTo(this.from.x, this.from.y);
  61. context.quadraticCurveTo(this.controlPoint.x, this.controlPoint.y, this.to.x, this.to.y);
  62. context.stroke();
  63. };
  64. QuadraticCurve.prototype.serialize = function(recursive)
  65. {
  66. var data = Line.prototype.serialize.call(this, recursive);
  67. data.controlPoint = this.controlPoint.toArray();
  68. return data;
  69. };
  70. QuadraticCurve.prototype.parse = function(data, root)
  71. {
  72. Line.prototype.parse.call(this, data, root);
  73. this.controlPoint.fromArray(data.controlPoint);
  74. };
  75. export {QuadraticCurve};