💾ctx.roundedRect()

browsercanvaspath ⟩ ctx.roundedRect()

💾 replit:roundedRect()

⬆️ require: arcTo()

// 🔸 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

};

Last updated