【问题标题】:canvas - Substract shape from a clipped canvascanvas - 从剪裁的画布中减去形状
【发布时间】:2016-09-22 12:10:10
【问题描述】:

我想通过 javascripts 画布从图像中剪辑出一个环形(即环)。 我已经有了一种方法,但我认为它太不雅了(而且我真的不明白为什么会这样,以及为什么它不会导致更小的圈子)。

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);

有没有更好的方法来做到这一点?

【问题讨论】:

  • 我没有得到目标。你不满意在canvas中画canvas吗?
  • @TheProHands 我想从已经剪裁的形状中剪裁出一个形状(在 Photoshop 中,您将其称为“从选择中减去”),而无需将临时图像绘制到第二个画布的额外步骤。我想要一个解决方案(或者至少想要解释我的解决方案)

标签: javascript html canvas clip


【解决方案1】:

这确实有效,因为 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>

【讨论】:

  • 完美,这就是我搜索的内容。如果你愿意,你可以编辑我的问题(以及标题更容易理解的问题),因为我认为其他用户也可能会觉得这很有用。
  • @InsOp,也不确定这个问题的最佳标题是什么......无论如何,很高兴它有所帮助。 Ps:其他 gCO 和 order 可以达到相同的结果,玩得开心;-)
猜你喜欢
  • 2015-01-28
  • 2016-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-26
  • 1970-01-01
  • 2015-08-14
相关资源
最近更新 更多