HTML5 Canvas - Fill circle with image

后端 未结 4 1228

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:49

    Not sure if you are still looking for the answer, but here's how:

    var ctx = document.getElementById('your_canvas').getContext("2d");
    //ctx.lineWidth = 13; 
    //ctx.strokeStyle = 'rgba(0,0,0,1)'; 
    //ctx.fillStyle="rgba(0,0,0,0)" // if using this, make sure alpha < 1
    
    ctx.arc(100,100, 50, 0, Math.PI*2,true); // you can use any shape
    ctx.clip();
    
    var img = new Image();
    img.addEventListener('load', function(e) {
        ctx.drawImage(this, 0, 0, 200, 300);
        //ctx.fill();
    //ctx.stroke();
    }, true);
    img.src="/path/to/image.jpg";
    

    You can also do this with pattern, but you get less image placement flexibility

    ctx.arc(100,100, 70, 0, Math.PI*2,true);
    ctx.clip();
    
    img = new Image()
    img.addEventListener('load', function(e) {
        ctx.fillStyle = ctx.createPattern(this, 'no-repeat') 
        ctx.fill();
    }, true);
    img.src="/path/to/image.jpg"
    

提交回复
热议问题