YouTip LogoYouTip

Canvas Closepath

## HTML Canvas closePath() Method The `closePath()` method of the Canvas 2D API attempts to close the current path by drawing a straight line from the current point back to the start of the current sub-path. If the shape has already been closed or has only one point, this method does nothing. --- ## Syntax and Usage ### JavaScript Syntax ```javascript context.closePath(); ``` ### How It Works * **Automatic Line Drawing:** When you call `closePath()`, the rendering context automatically adds a straight line segment from the current pen position back to the coordinates specified by the most recent `moveTo()` call. * **Creating Closed Shapes:** It is primarily used to create closed geometric shapes (like triangles, polygons, or closed custom paths) so that their strokes connect seamlessly. * **Stroke Joins:** Using `closePath()` ensures that the joint between the starting point and the ending point is properly styled using the `lineJoin` property (e.g., mitered, rounded, or beveled). Simply drawing a line back to the start point using `lineTo()` does not create a proper joint. --- ## Code Examples ### Example 1: Drawing a Closed Triangle (Stroke Only) This example draws an L-shaped path using two lines, and then uses `closePath()` to automatically draw the third line back to the starting point. ```html Your browser does not support the HTML5 canvas tag. ``` --- ### Example 2: Drawing and Filling a Closed Shape This example demonstrates how to close a path, outline it with a stroke, and fill it with a solid red color. ```html Your browser does not support the HTML5 canvas tag. ``` --- ## Key Considerations & Tips ### 1. `closePath()` vs. `fill()` * When you use the `fill()` method, the canvas will **automatically** close any open paths for you to fill the shape. * However, `fill()` does not draw an actual stroke outline. If you want to outline your shape using `stroke()`, you should explicitly call `closePath()` first to ensure the outline is fully closed and the line joints are rendered correctly. ### 2. Line Joints If you manually draw a line back to the starting point using `lineTo(startX, startY)` instead of using `closePath()`, the start and end of the line will overlap but will not be joined. This results in a visual gap or a flat edge at the corner. Calling `closePath()` ensures a perfect, continuous corner joint. ### 3. Starting a New Sub-path After calling `closePath()`, the next drawing command (like `lineTo()`) will implicitly start a new sub-path at the point where the previous path was closed. --- ## Browser Support The `closePath()` method is a core part of the HTML5 Canvas API and is supported by all modern web browsers: * Google Chrome * Microsoft Edge / Internet Explorer 9+ * Mozilla Firefox * Safari * Opera *Note: Internet Explorer 8 and earlier versions do not support the `` element.*
← Canvas LinetoCanvas Fill β†’