CanvasRenderingContext2D.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/OwnPtr.h>
  27. #include <LibGfx/Painter.h>
  28. #include <LibWeb/Bindings/CanvasRenderingContext2DWrapper.h>
  29. #include <LibWeb/HTML/CanvasRenderingContext2D.h>
  30. #include <LibWeb/HTML/HTMLCanvasElement.h>
  31. #include <LibWeb/HTML/HTMLImageElement.h>
  32. #include <LibWeb/HTML/ImageData.h>
  33. namespace Web::HTML {
  34. CanvasRenderingContext2D::CanvasRenderingContext2D(HTMLCanvasElement& element)
  35. : m_element(element)
  36. {
  37. }
  38. CanvasRenderingContext2D::~CanvasRenderingContext2D()
  39. {
  40. }
  41. void CanvasRenderingContext2D::set_fill_style(String style)
  42. {
  43. m_fill_style = Gfx::Color::from_string(style).value_or(Color::Black);
  44. }
  45. String CanvasRenderingContext2D::fill_style() const
  46. {
  47. return m_fill_style.to_string();
  48. }
  49. void CanvasRenderingContext2D::fill_rect(float x, float y, float width, float height)
  50. {
  51. auto painter = this->painter();
  52. if (!painter)
  53. return;
  54. auto rect = m_transform.map(Gfx::FloatRect(x, y, width, height));
  55. painter->fill_rect(enclosing_int_rect(rect), m_fill_style);
  56. did_draw(rect);
  57. }
  58. void CanvasRenderingContext2D::clear_rect(float x, float y, float width, float height)
  59. {
  60. auto painter = this->painter();
  61. if (!painter)
  62. return;
  63. auto rect = m_transform.map(Gfx::FloatRect(x, y, width, height));
  64. painter->clear_rect(enclosing_int_rect(rect), Color());
  65. did_draw(rect);
  66. }
  67. void CanvasRenderingContext2D::set_stroke_style(String style)
  68. {
  69. m_stroke_style = Gfx::Color::from_string(style).value_or(Color::Black);
  70. }
  71. String CanvasRenderingContext2D::stroke_style() const
  72. {
  73. return m_fill_style.to_string();
  74. }
  75. void CanvasRenderingContext2D::stroke_rect(float x, float y, float width, float height)
  76. {
  77. auto painter = this->painter();
  78. if (!painter)
  79. return;
  80. auto rect = m_transform.map(Gfx::FloatRect(x, y, width, height));
  81. auto top_left = m_transform.map(Gfx::FloatPoint(x, y)).to_type<int>();
  82. auto top_right = m_transform.map(Gfx::FloatPoint(x + width - 1, y)).to_type<int>();
  83. auto bottom_left = m_transform.map(Gfx::FloatPoint(x, y + height - 1)).to_type<int>();
  84. auto bottom_right = m_transform.map(Gfx::FloatPoint(x + width - 1, y + height - 1)).to_type<int>();
  85. painter->draw_line(top_left, top_right, m_stroke_style, m_line_width);
  86. painter->draw_line(top_right, bottom_right, m_stroke_style, m_line_width);
  87. painter->draw_line(bottom_right, bottom_left, m_stroke_style, m_line_width);
  88. painter->draw_line(bottom_left, top_left, m_stroke_style, m_line_width);
  89. did_draw(rect);
  90. }
  91. void CanvasRenderingContext2D::draw_image(const HTMLImageElement& image_element, float x, float y)
  92. {
  93. if (!image_element.bitmap())
  94. return;
  95. auto painter = this->painter();
  96. if (!painter)
  97. return;
  98. auto src_rect = image_element.bitmap()->rect();
  99. Gfx::FloatRect dst_rect = { x, y, (float)image_element.bitmap()->width(), (float)image_element.bitmap()->height() };
  100. auto rect = m_transform.map(dst_rect);
  101. painter->draw_scaled_bitmap(enclosing_int_rect(rect), *image_element.bitmap(), src_rect);
  102. }
  103. void CanvasRenderingContext2D::scale(float sx, float sy)
  104. {
  105. dbgln("CanvasRenderingContext2D::scale({}, {})", sx, sy);
  106. m_transform.scale(sx, sy);
  107. }
  108. void CanvasRenderingContext2D::translate(float tx, float ty)
  109. {
  110. dbgln("CanvasRenderingContext2D::translate({}, {})", tx, ty);
  111. m_transform.translate(tx, ty);
  112. }
  113. void CanvasRenderingContext2D::rotate(float radians)
  114. {
  115. dbgln("CanvasRenderingContext2D::rotate({})", radians);
  116. m_transform.rotate_radians(radians);
  117. }
  118. void CanvasRenderingContext2D::did_draw(const Gfx::FloatRect&)
  119. {
  120. // FIXME: Make use of the rect to reduce the invalidated area when possible.
  121. if (!m_element)
  122. return;
  123. if (!m_element->layout_node())
  124. return;
  125. m_element->layout_node()->set_needs_display();
  126. }
  127. OwnPtr<Gfx::Painter> CanvasRenderingContext2D::painter()
  128. {
  129. if (!m_element)
  130. return {};
  131. if (!m_element->bitmap()) {
  132. if (!m_element->create_bitmap())
  133. return {};
  134. }
  135. return make<Gfx::Painter>(*m_element->bitmap());
  136. }
  137. void CanvasRenderingContext2D::fill_text(const String& text, float x, float y, Optional<double> max_width)
  138. {
  139. if (max_width.has_value() && max_width.value() <= 0)
  140. return;
  141. auto painter = this->painter();
  142. if (!painter)
  143. return;
  144. // FIXME: painter only supports integer rects for text right now, so this effectively chops off any fractional position
  145. auto text_rect = Gfx::IntRect(x, y, max_width.has_value() ? max_width.value() : painter->font().width(text), painter->font().glyph_height());
  146. auto transformed_rect = m_transform.map(text_rect);
  147. painter->draw_text(transformed_rect, text, Gfx::TextAlignment::TopLeft, m_fill_style);
  148. did_draw(transformed_rect.to<float>());
  149. }
  150. void CanvasRenderingContext2D::begin_path()
  151. {
  152. m_path = Gfx::Path();
  153. }
  154. void CanvasRenderingContext2D::close_path()
  155. {
  156. m_path.close();
  157. }
  158. void CanvasRenderingContext2D::move_to(float x, float y)
  159. {
  160. m_path.move_to({ x, y });
  161. }
  162. void CanvasRenderingContext2D::line_to(float x, float y)
  163. {
  164. m_path.line_to({ x, y });
  165. }
  166. void CanvasRenderingContext2D::quadratic_curve_to(float cx, float cy, float x, float y)
  167. {
  168. m_path.quadratic_bezier_curve_to({ cx, cy }, { x, y });
  169. }
  170. DOM::ExceptionOr<void> CanvasRenderingContext2D::arc(float x, float y, float radius, float start_angle, float end_angle, bool counter_clockwise)
  171. {
  172. if (radius < 0)
  173. return DOM::IndexSizeError::create(String::formatted("The radius provided ({}) is negative.", radius));
  174. return ellipse(x, y, radius, radius, 0, start_angle, end_angle, counter_clockwise);
  175. }
  176. DOM::ExceptionOr<void> CanvasRenderingContext2D::ellipse(float x, float y, float radius_x, float radius_y, float rotation, float start_angle, float end_angle, bool counter_clockwise)
  177. {
  178. if (radius_x < 0)
  179. return DOM::IndexSizeError::create(String::formatted("The major-axis radius provided ({}) is negative.", radius_x));
  180. if (radius_y < 0)
  181. return DOM::IndexSizeError::create(String::formatted("The minor-axis radius provided ({}) is negative.", radius_y));
  182. if (constexpr float tau = M_TAU; (!counter_clockwise && (end_angle - start_angle) >= tau)
  183. || (counter_clockwise && (start_angle - end_angle) >= tau)) {
  184. start_angle = 0;
  185. end_angle = tau;
  186. } else {
  187. start_angle = fmodf(start_angle, tau);
  188. end_angle = fmodf(end_angle, tau);
  189. }
  190. // Then, figure out where the ends of the arc are.
  191. // To do so, we can pretend that the center of this ellipse is at (0, 0),
  192. // and the whole coordinate system is rotated `rotation` radians around the x axis, centered on `center`.
  193. // The sign of the resulting relative positions is just whether our angle is on one of the left quadrants.
  194. auto sin_rotation = sinf(rotation);
  195. auto cos_rotation = cosf(rotation);
  196. auto resolve_point_with_angle = [&](float angle) {
  197. auto tan_relative = tanf(angle);
  198. auto tan2 = tan_relative * tan_relative;
  199. auto ab = radius_x * radius_y;
  200. auto a2 = radius_x * radius_x;
  201. auto b2 = radius_y * radius_y;
  202. auto sqrt = sqrtf(b2 + a2 * tan2);
  203. auto relative_x_position = ab / sqrt;
  204. auto relative_y_position = ab * tan_relative / sqrt;
  205. // Make sure to set the correct sign
  206. float sn = sinf(angle) >= 0 ? 1 : -1;
  207. relative_x_position *= sn;
  208. relative_y_position *= sn;
  209. // Now rotate it (back) around the center point by 'rotation' radians, then move it back to our actual origin.
  210. auto relative_rotated_x_position = relative_x_position * cos_rotation - relative_y_position * sin_rotation;
  211. auto relative_rotated_y_position = relative_x_position * sin_rotation + relative_y_position * cos_rotation;
  212. return Gfx::FloatPoint { relative_rotated_x_position + x, relative_rotated_y_position + y };
  213. };
  214. auto start_point = resolve_point_with_angle(start_angle);
  215. auto end_point = resolve_point_with_angle(end_angle);
  216. m_path.move_to(start_point);
  217. double delta_theta = end_angle - start_angle;
  218. // FIXME: This is still goofy for some values.
  219. m_path.elliptical_arc_to(end_point, { radius_x, radius_y }, rotation, delta_theta > M_PI, !counter_clockwise);
  220. m_path.close();
  221. return {};
  222. }
  223. void CanvasRenderingContext2D::rect(float x, float y, float width, float height)
  224. {
  225. m_path.move_to({ x, y });
  226. if (width == 0 || height == 0)
  227. return;
  228. m_path.line_to({ x + width, y });
  229. m_path.line_to({ x + width, y + height });
  230. m_path.line_to({ x, y + height });
  231. m_path.close();
  232. }
  233. void CanvasRenderingContext2D::stroke()
  234. {
  235. auto painter = this->painter();
  236. if (!painter)
  237. return;
  238. painter->stroke_path(m_path, m_stroke_style, m_line_width);
  239. did_draw(m_path.bounding_box());
  240. }
  241. void CanvasRenderingContext2D::fill(Gfx::Painter::WindingRule winding)
  242. {
  243. auto painter = this->painter();
  244. if (!painter)
  245. return;
  246. auto path = m_path;
  247. path.close_all_subpaths();
  248. painter->fill_path(path, m_fill_style, winding);
  249. did_draw(m_path.bounding_box());
  250. }
  251. void CanvasRenderingContext2D::fill(const String& fill_rule)
  252. {
  253. if (fill_rule == "evenodd")
  254. return fill(Gfx::Painter::WindingRule::EvenOdd);
  255. return fill(Gfx::Painter::WindingRule::Nonzero);
  256. }
  257. RefPtr<ImageData> CanvasRenderingContext2D::create_image_data(int width, int height) const
  258. {
  259. if (!wrapper()) {
  260. dbgln("Hmm! Attempted to create ImageData for wrapper-less CRC2D.");
  261. return {};
  262. }
  263. return ImageData::create_with_size(wrapper()->global_object(), width, height);
  264. }
  265. void CanvasRenderingContext2D::put_image_data(const ImageData& image_data, float x, float y)
  266. {
  267. auto painter = this->painter();
  268. if (!painter)
  269. return;
  270. painter->blit(Gfx::IntPoint(x, y), image_data.bitmap(), image_data.bitmap().rect());
  271. did_draw(Gfx::FloatRect(x, y, image_data.width(), image_data.height()));
  272. }
  273. }