HTML5 Canvas - Fill circle with image

后端 未结 4 1235

How can I draw an image inside a circle? If I do:

context.beginPath();
context.arc((e.pageX),(e.pageY),161,0,Math.PI*2,true);
context.closePath();

4条回答
  •  孤独总比滥情好
    2020-11-30 22:42

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

    var thumbImg = document.createElement('img');
    
    thumbImg.src = '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/

提交回复
热议问题