CanvasPath.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. /*
  2. * Copyright (c) 2020-2022, Andreas Kling <andreas@ladybird.org>
  3. * Copyright (c) 2022, Sam Atkins <atkinssj@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibGfx/Vector2.h>
  8. #include <LibWeb/HTML/Canvas/CanvasPath.h>
  9. namespace Web::HTML {
  10. Gfx::AffineTransform CanvasPath::active_transform() const
  11. {
  12. if (m_canvas_state.has_value())
  13. return m_canvas_state->drawing_state().transform;
  14. return {};
  15. }
  16. void CanvasPath::ensure_subpath(float x, float y)
  17. {
  18. if (m_path.is_empty())
  19. m_path.move_to(Gfx::FloatPoint { x, y });
  20. }
  21. void CanvasPath::close_path()
  22. {
  23. m_path.close();
  24. }
  25. // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-moveto
  26. void CanvasPath::move_to(float x, float y)
  27. {
  28. // 1. If either of the arguments are infinite or NaN, then return.
  29. if (!isfinite(x) || !isfinite(y))
  30. return;
  31. // 2. Create a new subpath with the specified point as its first (and only) point.
  32. m_path.move_to(Gfx::FloatPoint { x, y });
  33. }
  34. // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-lineto
  35. void CanvasPath::line_to(float x, float y)
  36. {
  37. // 1. If either of the arguments are infinite or NaN, then return.
  38. if (!isfinite(x) || !isfinite(y))
  39. return;
  40. if (m_path.is_empty()) {
  41. // 2. If the object's path has no subpaths, then ensure there is a subpath for (x, y).
  42. ensure_subpath(x, y);
  43. } else {
  44. // 3. Otherwise, connect the last point in the subpath to the given point (x, y) using a straight line,
  45. // and then add the given point (x, y) to the subpath.
  46. m_path.line_to(Gfx::FloatPoint { x, y });
  47. }
  48. }
  49. // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-quadraticcurveto
  50. void CanvasPath::quadratic_curve_to(float cpx, float cpy, float x, float y)
  51. {
  52. // 1. If any of the arguments are infinite or NaN, then return.
  53. if (!isfinite(cpx) || !isfinite(cpy) || !isfinite(x) || !isfinite(y))
  54. return;
  55. // 2. Ensure there is a subpath for (cpx, cpy)
  56. ensure_subpath(cpx, cpy);
  57. // 3. Connect the last point in the subpath to the given point (x, y) using a quadratic Bézier curve with control point (cpx, cpy).
  58. // 4. Add the given point (x, y) to the subpath.
  59. m_path.quadratic_bezier_curve_to(Gfx::FloatPoint { cpx, cpy }, Gfx::FloatPoint { x, y });
  60. }
  61. // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-beziercurveto
  62. void CanvasPath::bezier_curve_to(double cp1x, double cp1y, double cp2x, double cp2y, double x, double y)
  63. {
  64. // 1. If any of the arguments are infinite or NaN, then return.
  65. if (!isfinite(cp1x) || !isfinite(cp1y) || !isfinite(cp2x) || !isfinite(cp2y) || !isfinite(x) || !isfinite(y))
  66. return;
  67. // 2. Ensure there is a subpath for (cp1x, cp1y)
  68. ensure_subpath(cp1x, cp1y);
  69. // 3. Connect the last point in the subpath to the given point (x, y) using a cubic Bézier curve with control poits (cp1x, cp1y) and (cp2x, cp2y).
  70. // 4. Add the point (x, y) to the subpath.
  71. m_path.cubic_bezier_curve_to(
  72. Gfx::FloatPoint { cp1x, cp1y }, Gfx::FloatPoint { cp2x, cp2y }, Gfx::FloatPoint { x, y });
  73. }
  74. WebIDL::ExceptionOr<void> CanvasPath::arc(float x, float y, float radius, float start_angle, float end_angle, bool counter_clockwise)
  75. {
  76. if (radius < 0)
  77. return WebIDL::IndexSizeError::create(m_self->realm(), MUST(String::formatted("The radius provided ({}) is negative.", radius)));
  78. return ellipse(x, y, radius, radius, 0, start_angle, end_angle, counter_clockwise);
  79. }
  80. // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-ellipse
  81. WebIDL::ExceptionOr<void> CanvasPath::ellipse(float x, float y, float radius_x, float radius_y, float rotation, float start_angle, float end_angle, bool counter_clockwise)
  82. {
  83. // 1. If any of the arguments are infinite or NaN, then return.
  84. if (!isfinite(x) || !isfinite(y) || !isfinite(radius_x) || !isfinite(radius_y) || !isfinite(rotation) || !isfinite(start_angle) || !isfinite(end_angle))
  85. return {};
  86. // 2. If either radiusX or radiusY are negative, then throw an "IndexSizeError" DOMException.
  87. if (radius_x < 0)
  88. return WebIDL::IndexSizeError::create(m_self->realm(), MUST(String::formatted("The major-axis radius provided ({}) is negative.", radius_x)));
  89. if (radius_y < 0)
  90. return WebIDL::IndexSizeError::create(m_self->realm(), MUST(String::formatted("The minor-axis radius provided ({}) is negative.", radius_y)));
  91. // "If counterclockwise is false and endAngle − startAngle is greater than or equal to 2π,
  92. // or, if counterclockwise is true and startAngle − endAngle is greater than or equal to 2π,
  93. // then the arc is the whole circumference of this ellipse"
  94. // Also draw the full ellipse if making a non-zero whole number of turns.
  95. if (constexpr float tau = M_PI * 2; (!counter_clockwise && (end_angle - start_angle) >= tau)
  96. || (counter_clockwise && (start_angle - end_angle) >= tau)
  97. || (start_angle != end_angle && fmodf(start_angle - end_angle, tau) == 0)) {
  98. start_angle = 0;
  99. // FIXME: elliptical_arc_to() incorrectly handles the case where the start/end points are very close.
  100. // So we slightly fudge the numbers here to correct for that.
  101. end_angle = tau * 0.9999f;
  102. counter_clockwise = false;
  103. } else {
  104. start_angle = fmodf(start_angle, tau);
  105. end_angle = fmodf(end_angle, tau);
  106. }
  107. // Then, figure out where the ends of the arc are.
  108. // To do so, we can pretend that the center of this ellipse is at (0, 0),
  109. // and the whole coordinate system is rotated `rotation` radians around the x axis, centered on `center`.
  110. // The sign of the resulting relative positions is just whether our angle is on one of the left quadrants.
  111. float sin_rotation;
  112. float cos_rotation;
  113. AK::sincos(rotation, sin_rotation, cos_rotation);
  114. auto resolve_point_with_angle = [&](float angle) {
  115. auto tan_relative = tanf(angle);
  116. auto tan2 = tan_relative * tan_relative;
  117. auto ab = radius_x * radius_y;
  118. auto a2 = radius_x * radius_x;
  119. auto b2 = radius_y * radius_y;
  120. auto sqrt = sqrtf(b2 + a2 * tan2);
  121. auto relative_x_position = ab / sqrt;
  122. auto relative_y_position = ab * tan_relative / sqrt;
  123. // Make sure to set the correct sign
  124. // -1 if 0 ≤ θ < 90° or 270°< θ ≤ 360°
  125. // 1 if 90° < θ< 270°
  126. float sn = cosf(angle) >= 0 ? 1 : -1;
  127. relative_x_position *= sn;
  128. relative_y_position *= sn;
  129. // Now rotate it (back) around the center point by 'rotation' radians, then move it back to our actual origin.
  130. auto relative_rotated_x_position = relative_x_position * cos_rotation - relative_y_position * sin_rotation;
  131. auto relative_rotated_y_position = relative_x_position * sin_rotation + relative_y_position * cos_rotation;
  132. return Gfx::FloatPoint { relative_rotated_x_position + x, relative_rotated_y_position + y };
  133. };
  134. auto start_point = resolve_point_with_angle(start_angle);
  135. auto end_point = resolve_point_with_angle(end_angle);
  136. float delta_theta;
  137. if (counter_clockwise) {
  138. delta_theta = start_angle - end_angle;
  139. } else {
  140. delta_theta = end_angle - start_angle;
  141. }
  142. if (delta_theta < 0)
  143. delta_theta += AK::Pi<float> * 2;
  144. // 3. If canvasPath's path has any subpaths, then add a straight line from the last point in the subpath to the start point of the arc.
  145. if (!m_path.is_empty())
  146. m_path.line_to(start_point);
  147. else
  148. m_path.move_to(start_point);
  149. // 4. Add the start and end points of the arc to the subpath, and connect them with an arc.
  150. m_path.elliptical_arc_to(
  151. Gfx::FloatPoint { end_point },
  152. Gfx::FloatSize { radius_x, radius_y },
  153. rotation,
  154. delta_theta > AK::Pi<float>, !counter_clockwise);
  155. return {};
  156. }
  157. // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-arcto
  158. WebIDL::ExceptionOr<void> CanvasPath::arc_to(double x1, double y1, double x2, double y2, double radius)
  159. {
  160. // 1. If any of the arguments are infinite or NaN, then return.
  161. if (!isfinite(x1) || !isfinite(y1) || !isfinite(x2) || !isfinite(y2) || !isfinite(radius))
  162. return {};
  163. // 2. Ensure there is a subpath for (x1, y1).
  164. ensure_subpath(x1, y1);
  165. // 3. If radius is negative, then throw an "IndexSizeError" DOMException.
  166. if (radius < 0)
  167. return WebIDL::IndexSizeError::create(m_self->realm(), MUST(String::formatted("The radius provided ({}) is negative.", radius)));
  168. auto transform = active_transform();
  169. // 4. Let the point (x0, y0) be the last point in the subpath,
  170. // transformed by the inverse of the current transformation matrix
  171. // (so that it is in the same coordinate system as the points passed to the method).
  172. // Point (x0, y0)
  173. auto p0 = transform.inverse().value_or(Gfx::AffineTransform()).map(m_path.last_point());
  174. // Point (x1, y1)
  175. auto p1 = Gfx::FloatPoint { x1, y1 };
  176. // Point (x2, y2)
  177. auto p2 = Gfx::FloatPoint { x2, y2 };
  178. // 5. If the point (x0, y0) is equal to the point (x1, y1),
  179. // or if the point (x1, y1) is equal to the point (x2, y2),
  180. // or if radius is zero, then add the point (x1, y1) to the subpath,
  181. // and connect that point to the previous point (x0, y0) by a straight line.
  182. if (p0 == p1 || p1 == p2 || radius == 0) {
  183. m_path.line_to(p1);
  184. return {};
  185. }
  186. auto v1 = Gfx::FloatVector2 { p0.x() - p1.x(), p0.y() - p1.y() };
  187. auto v2 = Gfx::FloatVector2 { p2.x() - p1.x(), p2.y() - p1.y() };
  188. auto cos_theta = v1.dot(v2) / (v1.length() * v2.length());
  189. // 6. Otherwise, if the points (x0, y0), (x1, y1), and (x2, y2) all lie on a single straight line,
  190. // then add the point (x1, y1) to the subpath,
  191. // and connect that point to the previous point (x0, y0) by a straight line.
  192. if (-1 == cos_theta || 1 == cos_theta) {
  193. m_path.line_to(p1);
  194. return {};
  195. }
  196. // 7. Otherwise, let The Arc be the shortest arc given by circumference of the circle that has radius radius,
  197. // and that has one point tangent to the half-infinite line that crosses the point (x0, y0) and ends at the point (x1, y1),
  198. // and that has a different point tangent to the half-infinite line that ends at the point (x1, y1) and crosses the point (x2, y2).
  199. // The points at which this circle touches these two lines are called the start and end tangent points respectively.
  200. auto adjacent = radius / static_cast<double>(tan(acos(cos_theta) / 2));
  201. auto factor1 = adjacent / static_cast<double>(v1.length());
  202. auto x3 = static_cast<double>(p1.x()) + factor1 * static_cast<double>(p0.x() - p1.x());
  203. auto y3 = static_cast<double>(p1.y()) + factor1 * static_cast<double>(p0.y() - p1.y());
  204. auto start_tangent = Gfx::FloatPoint { x3, y3 };
  205. auto factor2 = adjacent / static_cast<double>(v2.length());
  206. auto x4 = static_cast<double>(p1.x()) + factor2 * static_cast<double>(p2.x() - p1.x());
  207. auto y4 = static_cast<double>(p1.y()) + factor2 * static_cast<double>(p2.y() - p1.y());
  208. auto end_tangent = Gfx::FloatPoint { x4, y4 };
  209. // Connect the point (x0, y0) to the start tangent point by a straight line, adding the start tangent point to the subpath.
  210. m_path.line_to(start_tangent);
  211. bool const large_arc = false; // always small since tangent points define arc endpoints and lines meet at (x1, y1)
  212. auto cross_product = v1.x() * v2.y() - v1.y() * v2.x();
  213. bool const sweep = cross_product < 0; // right-hand rule, true means clockwise
  214. // and then connect the start tangent point to the end tangent point by The Arc, adding the end tangent point to the subpath.
  215. m_path.arc_to(end_tangent, radius, large_arc, sweep);
  216. return {};
  217. }
  218. // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-rect
  219. void CanvasPath::rect(double x, double y, double w, double h)
  220. {
  221. // 1. If any of the arguments are infinite or NaN, then return.
  222. if (!isfinite(x) || !isfinite(y) || !isfinite(w) || !isfinite(h))
  223. return;
  224. // 2. Create a new subpath containing just the four points (x, y), (x+w, y), (x+w, y+h), (x, y+h), in that order, with those four points connected by straight lines.
  225. m_path.move_to(Gfx::FloatPoint { x, y });
  226. m_path.line_to(Gfx::FloatPoint { x + w, y });
  227. m_path.line_to(Gfx::FloatPoint { x + w, y + h });
  228. m_path.line_to(Gfx::FloatPoint { x, y + h });
  229. // 3. Mark the subpath as closed.
  230. m_path.close();
  231. // 4. Create a new subpath with the point (x, y) as the only point in the subpath.
  232. m_path.move_to(Gfx::FloatPoint { x, y });
  233. }
  234. // https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-roundrect
  235. WebIDL::ExceptionOr<void> CanvasPath::round_rect(double x, double y, double w, double h, Variant<double, Geometry::DOMPointInit, Vector<Variant<double, Geometry::DOMPointInit>>> radii)
  236. {
  237. using Radius = Variant<double, Geometry::DOMPointInit>;
  238. // 1. If any of x, y, w, or h are infinite or NaN, then return.
  239. if (!isfinite(x) || !isfinite(y) || !isfinite(w) || !isfinite(h))
  240. return {};
  241. // 2. If radii is an unrestricted double or DOMPointInit, then set radii to « radii ».
  242. if (radii.has<double>() || radii.has<Geometry::DOMPointInit>()) {
  243. Vector<Radius> radii_list;
  244. if (radii.has<double>())
  245. radii_list.append(radii.get<double>());
  246. else
  247. radii_list.append(radii.get<Geometry::DOMPointInit>());
  248. radii = radii_list;
  249. }
  250. // 3. If radii is not a list of size one, two, three, or four, then throw a RangeError.
  251. if (radii.get<Vector<Radius>>().is_empty() || radii.get<Vector<Radius>>().size() > 4)
  252. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "roundRect: Can have between 1 and 4 radii"sv };
  253. // 4. Let normalizedRadii be an empty list.
  254. Vector<Geometry::DOMPointInit> normalized_radii;
  255. // 5. For each radius of radii:
  256. for (auto const& radius : radii.get<Vector<Radius>>()) {
  257. // 5.1. If radius is a DOMPointInit:
  258. if (radius.has<Geometry::DOMPointInit>()) {
  259. auto const& radius_as_dom_point = radius.get<Geometry::DOMPointInit>();
  260. // 5.1.1. If radius["x"] or radius["y"] is infinite or NaN, then return.
  261. if (!isfinite(radius_as_dom_point.x) || !isfinite(radius_as_dom_point.y))
  262. return {};
  263. // 5.1.2. If radius["x"] or radius["y"] is negative, then throw a RangeError.
  264. if (radius_as_dom_point.x < 0 || radius_as_dom_point.y < 0)
  265. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "roundRect: Radius can't be negative"sv };
  266. // 5.1.3. Otherwise, append radius to normalizedRadii.
  267. normalized_radii.append(radius_as_dom_point);
  268. }
  269. // 5.2. If radius is a unrestricted double:
  270. if (radius.has<double>()) {
  271. auto radius_as_double = radius.get<double>();
  272. // 5.2.1. If radius is infinite or NaN, then return.
  273. if (!isfinite(radius_as_double))
  274. return {};
  275. // 5.2.2. If radius is negative, then throw a RangeError.
  276. if (radius_as_double < 0)
  277. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "roundRect: Radius can't be negative"sv };
  278. // 5.2.3. Otherwise append «[ "x" → radius, "y" → radius ]» to normalizedRadii.
  279. normalized_radii.append(Geometry::DOMPointInit { radius_as_double, radius_as_double });
  280. }
  281. }
  282. // 6. Let upperLeft, upperRight, lowerRight, and lowerLeft be null.
  283. Geometry::DOMPointInit upper_left {};
  284. Geometry::DOMPointInit upper_right {};
  285. Geometry::DOMPointInit lower_right {};
  286. Geometry::DOMPointInit lower_left {};
  287. // 7. If normalizedRadii's size is 4, then set upperLeft to normalizedRadii[0], set upperRight to normalizedRadii[1], set lowerRight to normalizedRadii[2], and set lowerLeft to normalizedRadii[3].
  288. if (normalized_radii.size() == 4) {
  289. upper_left = normalized_radii.at(0);
  290. upper_right = normalized_radii.at(1);
  291. lower_right = normalized_radii.at(2);
  292. lower_left = normalized_radii.at(3);
  293. }
  294. // 8. If normalizedRadii's size is 3, then set upperLeft to normalizedRadii[0], set upperRight and lowerLeft to normalizedRadii[1], and set lowerRight to normalizedRadii[2].
  295. if (normalized_radii.size() == 3) {
  296. upper_left = normalized_radii.at(0);
  297. upper_right = lower_left = normalized_radii.at(1);
  298. lower_right = normalized_radii.at(2);
  299. }
  300. // 9. If normalizedRadii's size is 2, then set upperLeft and lowerRight to normalizedRadii[0] and set upperRight and lowerLeft to normalizedRadii[1].
  301. if (normalized_radii.size() == 2) {
  302. upper_left = lower_right = normalized_radii.at(0);
  303. upper_right = lower_left = normalized_radii.at(1);
  304. }
  305. // 10. If normalizedRadii's size is 1, then set upperLeft, upperRight, lowerRight, and lowerLeft to normalizedRadii[0].
  306. if (normalized_radii.size() == 1)
  307. upper_left = upper_right = lower_right = lower_left = normalized_radii.at(0);
  308. // 11. Corner curves must not overlap. Scale all radii to prevent this:
  309. // 11.1. Let top be upperLeft["x"] + upperRight["x"].
  310. double top = upper_left.x + upper_right.x;
  311. // 11.2. Let right be upperRight["y"] + lowerRight["y"].
  312. double right = upper_right.y + lower_right.y;
  313. // 11.3. Let bottom be lowerRight["x"] + lowerLeft["x"].
  314. double bottom = lower_right.x + lower_left.x;
  315. // 11.4. Let left be upperLeft["y"] + lowerLeft["y"].
  316. double left = upper_left.y + lower_left.y;
  317. // 11.5. Let scale be the minimum value of the ratios w / top, h / right, w / bottom, h / left.
  318. double scale = AK::min(AK::min(w / top, h / right), AK::min(w / bottom, h / left));
  319. // 11.6. If scale is less than 1, then set the x and y members of upperLeft, upperRight, lowerLeft, and lowerRight to their current values multiplied by scale.
  320. if (scale < 1) {
  321. upper_left.x *= scale;
  322. upper_left.y *= scale;
  323. upper_right.x *= scale;
  324. upper_right.y *= scale;
  325. lower_left.x *= scale;
  326. lower_left.y *= scale;
  327. lower_right.x *= scale;
  328. lower_right.y *= scale;
  329. }
  330. // 12. Create a new subpath:
  331. bool large_arc = false;
  332. bool sweep = true;
  333. // 12.1. Move to the point (x + upperLeft["x"], y).
  334. m_path.move_to(Gfx::FloatPoint { x + upper_left.x, y });
  335. // 12.2. Draw a straight line to the point (x + w − upperRight["x"], y).
  336. m_path.line_to(Gfx::FloatPoint { x + w - upper_right.x, y });
  337. // 12.3. Draw an arc to the point (x + w, y + upperRight["y"]).
  338. m_path.elliptical_arc_to(Gfx::FloatPoint { x + w, y + upper_right.y }, { upper_right.x, upper_right.y }, 0, large_arc, sweep);
  339. // 12.4. Draw a straight line to the point (x + w, y + h − lowerRight["y"]).
  340. m_path.line_to(Gfx::FloatPoint { x + w, y + h - lower_right.y });
  341. // 12.5. Draw an arc to the point (x + w − lowerRight["x"], y + h).
  342. m_path.elliptical_arc_to(Gfx::FloatPoint { x + w - lower_right.x, y + h }, { lower_right.x, lower_right.y }, 0, large_arc, sweep);
  343. // 12.6. Draw a straight line to the point (x + lowerLeft["x"], y + h).
  344. m_path.line_to(Gfx::FloatPoint { x + lower_left.x, y + h });
  345. // 12.7. Draw an arc to the point (x, y + h − lowerLeft["y"]).
  346. m_path.elliptical_arc_to(Gfx::FloatPoint { x, y + h - lower_left.y }, { lower_left.x, lower_left.y }, 0, large_arc, sweep);
  347. // 12.8. Draw a straight line to the point (x, y + upperLeft["y"]).
  348. m_path.line_to(Gfx::FloatPoint { x, y + upper_left.y });
  349. // 12.9. Draw an arc to the point (x + upperLeft["x"], y).
  350. m_path.elliptical_arc_to(Gfx::FloatPoint { x + upper_left.x, y }, { upper_left.x, upper_left.y }, 0, large_arc, sweep);
  351. // 13. Mark the subpath as closed.
  352. m_path.close();
  353. // 14. Create a new subpath with the point (x, y) as the only point in the subpath.
  354. m_path.move_to(Gfx::FloatPoint { x, y });
  355. return {};
  356. }
  357. }