0

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

Sainan
  • 1,274
  • 2
  • 19
  • 32
Cotne
  • 17
  • 1
  • 2
  • 2
    http://stackoverflow.com/questions/4276048/html5-canvas-fill-circle-with-image – Emil S. Jørgensen Oct 17 '16 at 11:16
  • Duplicate of [HTML5 Canvas - Fill circle with image](http://stackoverflow.com/questions/4276048/html5-canvas-fill-circle-with-image) – takendarkk Oct 17 '16 at 11:19
  • While the ultimate goal is the same, I disagree with these dupes CV since here it seems more like an incomprehension of how gCO works (which is btw a way better way of doing than the answers provided in the dupe.) – Kaiido Oct 17 '16 at 11:24

1 Answers1

0

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>
Kaiido
  • 123,334
  • 13
  • 219
  • 285
  • sorry I've not shown whole code , anyway this runs perfect but there is one problem I want image to move around. in arc(x,y...) i was changing x and y and it was good but now only background is changing . – Cotne Oct 17 '16 at 11:59
  • @Cotne you need to also change x and y values passed to `drawImage` – Kaiido Oct 17 '16 at 12:55