Applying a Circular Mask to an Image

Profile pictures are often masked by a circle. How can we present our images in such a circle. Lets explore two options, one where we actually mask the image data, and one where we use CSS.

Applying the mask using CSS

Applying a circular mask to an image using CSS is quite straightforward. We only have to set the border-radius property and we're done.

img {
    border-radius: 50%;

<img src="path/to/our/image.jpeg" alt="">

Applying the mask using Canvas

To modify the actual image data we can use the <canvas> element and apply the circular mask to the image itself.

To achieve this we use the Doka beforeCreateBlob hook, it'll receive the <canvas> element right before Doka turns it into a Blob. We can use the function to make some last minute modifications to the image data.

    beforeCreateBlob: canvas => new Promise((resolve, reject) => {

        // get the drawing context for our output image
        const ctx = canvas.getContext('2d');

        // only draw image where mask is
        ctx.globalCompositeOperation = 'destination-in';

        // draw our circle mask
        ctx.fillStyle = '#000';
            canvas.width * .5,  // x
            canvas.height * .5, // y
            canvas.width * .5,  // radius
            0,                  // start angle
            2 * Math.PI         // end angle

        // restore to default composite operation (is draw over current image)
        ctx.globalCompositeOperation = 'source-over';

        // return the canvas to Doka