我想通过 javascripts Canvas 从图像中剪下一个圆环(即环)。 我已经有了一种方法,但我认为它太不优雅了(而且我真的不明白为什么会这样,为什么它不会导致更小的圆圈)。
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/