Source: Circle.js

  1. import { Plot } from "./Plot.js";
  2. /** Class representing a circle. */
  3. export class Circle {
  4. /**
  5. * Create a circle.
  6. * @param {number} x - The x value of the centre.
  7. * @param {number} y - The y value of the centre.
  8. * @param {number} radius - The radius.
  9. * @param {Object} options
  10. * @param {string} [options.stroke = "black"]
  11. * @param {number} [options.strokeWidth = 0.1]
  12. * @param {string} [options.fill = "none"]
  13. */
  14. constructor(
  15. x,
  16. y,
  17. radius,
  18. { stroke, strokeWidth, fill = "none" } = {},
  19. ) {
  20. this.x = x;
  21. this.y = y;
  22. this.radius = radius;
  23. const plot = Plot.getContext();
  24. this.stroke = stroke !== undefined ? stroke : plot?.stroke || "black";
  25. this.strokeWidth = strokeWidth !== undefined ? strokeWidth : plot?.strokeWidth || 0.1;
  26. this.fill = fill;
  27. }
  28. /**
  29. * Create a circle from a Vector object and a radius.
  30. * @param {Vector} vector - The position of the centre of the circle.
  31. * @param {number} radius - The radius.
  32. * @returns {Circle}
  33. */
  34. static fromVector(vector, radius) {
  35. return new Circle(vector.x, vector.y, radius);
  36. }
  37. /**
  38. *
  39. * @returns {SVGElement}
  40. */
  41. toSVGElement() {
  42. let element = document.createElementNS(
  43. "http://www.w3.org/2000/svg",
  44. "circle",
  45. );
  46. element.setAttribute("cx", this.x);
  47. element.setAttribute("cy", this.y);
  48. element.setAttribute("r", this.radius);
  49. element.setAttribute("stroke", this.stroke);
  50. element.setAttribute("fill", this.fill);
  51. element.setAttribute("stroke-width", `${this.strokeWidth}`);
  52. return element;
  53. }
  54. }