canvas - 从剪裁中减去形状 canvas

canvas - Substract shape from a clipped canvas

我想通过 javascripts canvas 从图像中剪下一个圆环(即环)。 我已经有了一个方法,但我认为它太不雅观了(而且我真的不明白为什么会这样,为什么它不会导致更小的圆圈)。

see this jsfiddle

    context.drawImage(imageObj, 0, 0, 500, 500);

    //crop outer circle
    context2.beginPath();
    context2.arc(250, 250, 200, 0, 2 * Math.PI, false);
    context2.closePath();
    context2.clip();

    //draw circle
    context2.drawImage(canvas,0,0);

    //crop inner circle
    context2.beginPath();
    context2.arc(250, 250, 100, 0, 2 * Math.PI, false);
    context2.closePath();
    context2.clip();

    //clear context 2
    context2.clearRect(0,0,500,500)

    // finally draw annulus
    context2.drawImage(canvas2,0,0);

有更好的方法吗?

这确实有效,因为 clip 方法调用的裁剪区域会堆叠。

IMO,这确实不是最好的方法,因为你肯定需要在裁剪前调用 ctx.save(); 并在裁剪后调用 ctx.restore(),这是非常繁重的方法。

我的首选方法是使用 compositing :

var ctx = canvas.getContext('2d');

var imageObj = new Image();

imageObj.onload = function() {

  ctx.drawImage(imageObj, 0, 0, 500, 500);
  // keep only the outer circle
  ctx.globalCompositeOperation = 'destination-in';
  ctx.beginPath();
  ctx.arc(250, 250, 200, 0, 2 * Math.PI, false);
  ctx.fill();
  // remove the inner one
  ctx.globalCompositeOperation = 'destination-out';
  ctx.beginPath();
  ctx.arc(250, 250, 100, 0, 2 * Math.PI, false);
  ctx.fill();
  // reset gCO
  ctx.globalCompositeOperation = 'source-over';

};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
<canvas id="canvas" width="500" height="500"></canvas>