Skip to main content

round

The round() function draws a circular clipping region on a canvas context.

Parameters

ParameterTypeDescription
ctxCanvasRenderingContext2DThe canvas rendering context to draw on.
xnumberThe x-coordinate of the top-left corner of the rectangle.
ynumberThe y-coordinate of the top-left corner of the rectangle.
widthnumberThe width of the rectangle.
heightnumberThe height of the rectangle.
radiusnumber or boolean (optional)The radius of the corners, or true for a default radius. If not specified, the rectangle will have sharp edges.

Return value

  • (CanvasRenderingContext2D): The canvas context with the rounded rectangle drawn on it.

Throws

  • Error: Missing canvas context or invalid argument types.

Example

const { createCanvas, loadImage } = require('canvas');
const canvas = createCanvas(500, 500);
const ctx = canvas.getContext('2d');

// Draw a rounded rectangle clipping region in the center of the canvas
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = Math.min(canvas.width, canvas.height) / 4;
ctx.save();
round(ctx, centerX - radius, centerY - radius, radius * 2, radius * 2, 10);

// Draw an image that is clipped to the rounded rectangle region
const image = await loadImage('myImage.png');
ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
ctx.restore();
info

this example uses await to wait for the request which means the code has to be inside an async function.

See also