CanvasState.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright (c) 2021-2022, Linus Groh <linusg@serenityos.org>
  3. * Copyright (c) 2022, Sam Atkins <atkinssj@serenityos.org>
  4. * Copyright (c) 2023, MacDue <macdue@dueutil.tech>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <LibGfx/Painter.h>
  9. #include <LibWeb/HTML/Canvas/CanvasState.h>
  10. namespace Web::HTML {
  11. // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-save
  12. void CanvasState::save()
  13. {
  14. // The save() method steps are to push a copy of the current drawing state onto the drawing state stack.
  15. m_drawing_state_stack.append(m_drawing_state);
  16. if (auto* painter = painter_for_canvas_state())
  17. painter->save();
  18. }
  19. // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-restore
  20. void CanvasState::restore()
  21. {
  22. // The restore() method steps are to pop the top entry in the drawing state stack, and reset the drawing state it describes. If there is no saved state, then the method must do nothing.
  23. if (m_drawing_state_stack.is_empty())
  24. return;
  25. m_drawing_state = m_drawing_state_stack.take_last();
  26. if (auto* painter = painter_for_canvas_state())
  27. painter->restore();
  28. }
  29. // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-reset
  30. void CanvasState::reset()
  31. {
  32. // The reset() method steps are to reset the rendering context to its default state.
  33. reset_to_default_state();
  34. }
  35. // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-iscontextlost
  36. bool CanvasState::is_context_lost()
  37. {
  38. // The isContextLost() method steps are to return this's context lost.
  39. return m_context_lost;
  40. }
  41. NonnullRefPtr<Gfx::PaintStyle> CanvasState::FillOrStrokeStyle::to_gfx_paint_style()
  42. {
  43. return m_fill_or_stroke_style.visit(
  44. [&](Gfx::Color color) -> NonnullRefPtr<Gfx::PaintStyle> {
  45. if (!m_color_paint_style)
  46. m_color_paint_style = Gfx::SolidColorPaintStyle::create(color).release_value_but_fixme_should_propagate_errors();
  47. return m_color_paint_style.release_nonnull();
  48. },
  49. [&](auto handle) {
  50. return handle->to_gfx_paint_style();
  51. });
  52. }
  53. Gfx::Color CanvasState::FillOrStrokeStyle::to_color_but_fixme_should_accept_any_paint_style() const
  54. {
  55. return as_color().value_or(Gfx::Color::Black);
  56. }
  57. Optional<Gfx::Color> CanvasState::FillOrStrokeStyle::as_color() const
  58. {
  59. if (auto* color = m_fill_or_stroke_style.get_pointer<Gfx::Color>())
  60. return *color;
  61. return {};
  62. }
  63. }