HTML5 Canvas 清除圓形、不規(guī)則區(qū)域
原文地址:HTML5 Canvas 清除圓形、不規(guī)則區(qū)域
- clearRect
默認(rèn) Canvas Api 只提供了清除矩形區(qū)域的接口 clearRect(),但有時(shí)候需要清除圓形或其他特殊形狀的區(qū)域。
- ctx.globalCompositeOperation
ctx.globalCompositeOperation 提供了多種色彩合成模式,其中 destination-out 能夠完成清除效果
- source-over
這是默認(rèn)設(shè)置,并在現(xiàn)有畫(huà)布上下文之上繪制新圖形。
- destination-out
現(xiàn)有內(nèi)容保持在新圖形不重疊的地方。(優(yōu)點(diǎn)就是不會(huì)清空整個(gè)畫(huà)布,會(huì)保留之前以及繪制的部分)
CanvasRenderingContext2D.prototype.clearArc = function(x, y, radius, startAngle, endAngle, anticlockwise) {
this.beginPath();
this.globalCompositeOperation = 'destination-out';
this.fillStyle = 'black';
// 繪制新圖形
this.arc(x, y, radius, startAngle, endAngle, anticlockwise);
// 參數(shù)分別是:圓心橫坐標(biāo)、縱坐標(biāo)、半徑、開(kāi)始的角度、結(jié)束的角度、是否逆時(shí)針
this.fill();
this.closePath();
};
- 通過(guò)清空畫(huà)布也可以實(shí)現(xiàn)
// canvas每當(dāng)高度或?qū)挾缺恢卦O(shè)時(shí),畫(huà)布內(nèi)容就會(huì)被清空,所以會(huì)導(dǎo)致之前畫(huà)的圓都被刪除
function clearCanves(canvas, width, height) {
canvas.height = height;
canvas.width = width;
}