HTML5 Canvas – Fill circle with image

I did this the other day for a big thing I’m making;

var thumbImg = document.createElement('img');

thumbImg.src="https://stackoverflow.com/questions/4276048/path_to_image";
thumbImg.onload = function() {
    tmpCtx.save();
    tmpCtx.beginPath();
    tmpCtx.arc(25, 25, 25, 0, Math.PI * 2, true);
    tmpCtx.closePath();
    tmpCtx.clip();

    tmpCtx.drawImage(thumbImg, 0, 0, 50, 50);

    tmpCtx.beginPath();
    tmpCtx.arc(0, 0, 25, 0, Math.PI * 2, true);
    tmpCtx.clip();
    tmpCtx.closePath();
    tmpCtx.restore();
};

Worked perfect for me.

Here’s a more complex version of it that I made which does image caching too, https://jsfiddle.net/jaredwilli/ex5n5/

Leave a Comment