CanvasState.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 <LibWeb/HTML/Canvas/CanvasState.h>
  9. namespace Web::HTML {
  10. // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-save
  11. void CanvasState::save()
  12. {
  13. // The save() method steps are to push a copy of the current drawing state onto the drawing state stack.
  14. m_drawing_state_stack.append(m_drawing_state);
  15. }
  16. // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-restore
  17. void CanvasState::restore()
  18. {
  19. // 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.
  20. if (m_drawing_state_stack.is_empty())
  21. return;
  22. m_drawing_state = m_drawing_state_stack.take_last();
  23. }
  24. // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-reset
  25. void CanvasState::reset()
  26. {
  27. // The reset() method steps are to reset the rendering context to its default state.
  28. reset_to_default_state();
  29. }
  30. // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-iscontextlost
  31. bool CanvasState::is_context_lost()
  32. {
  33. // The isContextLost() method steps are to return this's context lost.
  34. return m_context_lost;
  35. }
  36. NonnullRefPtr<Gfx::PaintStyle> CanvasState::FillOrStrokeStyle::to_gfx_paint_style()
  37. {
  38. return m_fill_or_stroke_style.visit(
  39. [&](Gfx::Color color) -> NonnullRefPtr<Gfx::PaintStyle> {
  40. if (!m_color_paint_style)
  41. m_color_paint_style = Gfx::SolidColorPaintStyle::create(color).release_value_but_fixme_should_propagate_errors();
  42. return m_color_paint_style.release_nonnull();
  43. },
  44. [&](auto handle) {
  45. return handle->to_gfx_paint_style();
  46. });
  47. }
  48. Gfx::Color CanvasState::FillOrStrokeStyle::to_color_but_fixme_should_accept_any_paint_style() const
  49. {
  50. return as_color().value_or(Gfx::Color::Black);
  51. }
  52. Optional<Gfx::Color> CanvasState::FillOrStrokeStyle::as_color() const
  53. {
  54. if (auto* color = m_fill_or_stroke_style.get_pointer<Gfx::Color>())
  55. return *color;
  56. return {};
  57. }
  58. }