How can I add an image inside a circle in canvas?

2019-09-06 06:01发布

I want to insert this image

var img=new Image();
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/desert1.jpg";

Into the circle, that I'm drawing with this function

function drawBall() {
    //ctx.globalCompositeOperation='destination-in';
    ctx.beginPath();
    ctx.arc(x, y, ballRadius, 0, Math.PI*2);
    ctx.drawImage(img,10,20);
    ctx.globalCompositeOperation='source-over';
    ctx.fillStyle = "#0095DD";
    ctx.fill();
    ctx.closePath();
}

Here's what the canvas currently looks like:

exemplary rendering

1条回答
虎瘦雄心在
2楼-- · 2019-09-06 06:43

globalCompositeOperation mode source-over is the default gCO mode, which draws new content over the existing one.
You need to set it to destination-in after you've drawn something on the canvas, so only the pixels where both the new pixels and the already painted ones will overlap, stay.

var img=new Image();
img.onload = drawBall;
img.src="https://upload.wikimedia.org/wikipedia/commons/5/55/John_William_Waterhouse_A_Mermaid.jpg";

function drawBall() {
    var ctx = c.getContext('2d');
    c.width = this.width;
    c.height = this.height;
  
    // default gCO is source-over
    ctx.drawImage(img,-250,-200, img.width*.7, img.height*.7);
    // now we change the gCO
    ctx.globalCompositeOperation='destination-in';
    ctx.beginPath();
    ctx.arc(75, 75, 50, 0, Math.PI*2);
    ctx.fillStyle = "#0095DD";
    ctx.fill();
    // reset to default
    ctx.globalCompositeOperation='source-over';
    // closePath is useless here
    //ctx.closePath();
}
<canvas id="c"></canvas>

查看更多
登录 后发表回答