> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/browser/canvas/+ext/ctx.roundedrect.md).

# ctx.roundedRect()

[browser](/web/browser.md) ⟩ [canvas](/web/browser/canvas.md) ⟩ [path](/web/browser/canvas/path.md) ⟩ ctx.roundedRect()

{% tabs %}
{% tab title="💾 程式" %}
:floppy\_disk: replit：[roundedRect()](https://replit.com/@pegasusroe/canvas-roundedRect#script.js)

⬆️ require： [arcTo()](/web/browser/canvas/path/arcto.md)

```javascript
// 🔸 ctx.roundedRect()
CanvasRenderingContext2D.prototype.roundedRect = function(
    x, y, width, height, cornerRadius, {
    clockwise = true
} = {}) {

    const w = width, h = height;
    const r = Math.min(cornerRadius, width / 2, height / 2);

    // 4 corners
    const C1 = [x, y];
    const C2 = [x + w, y];
    const C3 = [x + w, y + h];
    const C4 = [x, y + h];

    // 4 control points
    const P1 = [x + r, y];
    const P2 = [x + w, y + r];
    const P3 = [x + w - r, y + h];
    const P4 = [x, y + h - r];

    this.moveTo(...P1);    // new subpath

    if (clockwise) {
        this.arcTo(...C2, ...P2, r);
        this.arcTo(...C3, ...P3, r);
        this.arcTo(...C4, ...P4, r);
        this.arcTo(...C1, ...P1, r);
    } else {
        this.arcTo(...C1, ...P4, r);
        this.arcTo(...C4, ...P3, r);
        this.arcTo(...C3, ...P2, r);
        this.arcTo(...C2, ...P1, r);
    }

    this.closePath();      // close subpath

};
```

{% endtab %}

{% tab title="💈範例" %}
![](https://2527454625-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MfvEFZnSBhKT6fJmus0%2Fuploads%2FyCqN1vYx77h7KztzoE3p%2Fcanvas%20rounded%20rect.png?alt=media\&token=ea51354d-7186-45ec-a637-2addaeccdc71)

⬆️ require： [drawOnCanvas2D()](/web/browser/canvas/+ext/drawoncanvas2d.md)

```javascript
drawOnCanvas2D('#playground', (ctx) => {
    
    const d = 20, w = 330, h = 80, r = 30, dx = 15;
    const P1 = [dx, dx], P2 = [dx + d, dx + d];
    const size = [w+d*2, h+d*2], size2 = [w, h];

    ctx.fillStyle = 'rgba(0, 200, 0, 0.5)';
    ctx.roundedRect(...P1, ...size, r+d);
    ctx.roundedRect(...P2, ...size2, r, {clockwise: false})
    ctx.fill();
    ctx.stroke();
    
});
```

{% endtab %}
{% endtabs %}
