💾ctx.roundedRect()
browser ⟩ canvas ⟩ path ⟩ 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
};
⬆️ require: drawOnCanvas2D()
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();
});
Last updated