CanvasGradient.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright (c) 2022, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/QuickSort.h>
  7. #include <LibWeb/DOM/ExceptionOr.h>
  8. #include <LibWeb/HTML/CanvasGradient.h>
  9. namespace Web::HTML {
  10. NonnullRefPtr<CanvasGradient> CanvasGradient::create_radial(double x0, double y0, double r0, double x1, double y1, double r1)
  11. {
  12. (void)x0;
  13. (void)y0;
  14. (void)r0;
  15. (void)x1;
  16. (void)y1;
  17. (void)r1;
  18. return adopt_ref(*new CanvasGradient(Type::Radial));
  19. }
  20. NonnullRefPtr<CanvasGradient> CanvasGradient::create_linear(double x0, double y0, double x1, double y1)
  21. {
  22. (void)x0;
  23. (void)y0;
  24. (void)x1;
  25. (void)y1;
  26. return adopt_ref(*new CanvasGradient(Type::Linear));
  27. }
  28. NonnullRefPtr<CanvasGradient> CanvasGradient::create_conic(double start_angle, double x, double y)
  29. {
  30. (void)start_angle;
  31. (void)x;
  32. (void)y;
  33. return adopt_ref(*new CanvasGradient(Type::Conic));
  34. }
  35. CanvasGradient::CanvasGradient(Type type)
  36. : m_type(type)
  37. {
  38. }
  39. CanvasGradient::~CanvasGradient() = default;
  40. // https://html.spec.whatwg.org/multipage/canvas.html#dom-canvasgradient-addcolorstop
  41. DOM::ExceptionOr<void> CanvasGradient::add_color_stop(double offset, String const& color)
  42. {
  43. // 1. If the offset is less than 0 or greater than 1, then throw an "IndexSizeError" DOMException.
  44. if (offset < 0 || offset > 1)
  45. return DOM::IndexSizeError::create("CanvasGradient color stop offset out of bounds");
  46. // 2. Let parsed color be the result of parsing color.
  47. auto parsed_color = Color::from_string(color);
  48. // 3. If parsed color is failure, throw a "SyntaxError" DOMException.
  49. if (!parsed_color.has_value())
  50. return DOM::SyntaxError::create("Could not parse color for CanvasGradient");
  51. // 4. Place a new stop on the gradient, at offset offset relative to the whole gradient, and with the color parsed color.
  52. m_color_stops.append(ColorStop { offset, parsed_color.value() });
  53. // FIXME: If multiple stops are added at the same offset on a gradient, then they must be placed in the order added,
  54. // with the first one closest to the start of the gradient, and each subsequent one infinitesimally further along
  55. // towards the end point (in effect causing all but the first and last stop added at each point to be ignored).
  56. quick_sort(m_color_stops, [](auto& a, auto& b) { return a.offset < b.offset; });
  57. return {};
  58. }
  59. }