javascript - canvas - 从裁剪的 Canvas 中减去形状

标签 javascript html canvas clip

我想通过 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>

关于javascript - canvas - 从裁剪的 Canvas 中减去形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39638694/

相关文章:

android - 屏幕尺寸变化时如何缩放线条的粗细或笔划宽度

javascript - 任何现有的 javascript 库可以更改 svg 填充颜色?动画优先

html - 为什么在附加到我的标签的 CSS 类中设置宽度不会改变它们的宽度?

javascript - 如何回发并在悬停时显示 div 并从数据库获取信息

javascript - 按比例调整图像大小以适应 HTML5 Canvas

java - 如何垂直对齐文本?

javascript - JS中如何减少函数内的重复代码

javascript - 在传单弹出窗口中显示图像

javascript - FUNCTION中如何返回为多维数组的输出

javascript - 无法使用 Mongoose 按日期获取集合