圖像重疊
globalCompositeOperation : 繪制的圖像,在重疊的時(shí)候所產(chǎn)生的效果(復(fù)合操作)
globalCompositeOperation = ‘source-over’ 默認(rèn) 后覆蓋前
globalCompositeOperation = 'destination-over' 前覆蓋后
| 屬性值 | 描述 |
|---|---|
| source-over | 新圖形會覆蓋原有內(nèi)容之上 |
| source-atop | 新圖形中與原有內(nèi)容重疊的部分會被繪制,并覆蓋于原來內(nèi)容之上 |
| source-in | 新圖形只會出現(xiàn)原有內(nèi)容重疊的部分,其他區(qū)域變成透明色 |
| source-out | 只有新圖形中與原有的內(nèi)容不重疊的部分被保留 |
| destination-over | 會在原有內(nèi)容之下繪制新圖形 |
| destination-atop | 原有內(nèi)容中與新內(nèi)容重疊的部分會被保留,并會在原有內(nèi)容之下繪制新圖形 |
| destination-in | 原有內(nèi)容中與新圖形重疊的部分會被保留,其它區(qū)域都變成透明的 |
| destination-out | : 原有內(nèi)容中與新圖形不重疊的部分會被保留。 |
| lighter | 兩圖形中重疊部分作加色處理。 |
| copy | 只有新圖形會被保留,其它都被清除掉 |
| xor | 重疊的部分會變成透明 |
| darker | 兩圖形中重疊的部分作減色處理 |

operation.gif
代碼
HTML
<div id="types">
<span class="active">source-over</span>
<span>source-atop</span>
<span>source-in</span>
<span>source-out</span>
<hr>
<span>destination-over</span>
<span>destination-atop</span>
<span>destination-in</span>
<span>destination-out</span>
<hr>
<span>lighter</span>
<span>copy</span>
<span>xor</span>
<span>darker</span>
</div>
<div>
<pre>
// source-over: 新圖形會覆蓋原有內(nèi)容之上
// source-atop: 新圖形中與原有內(nèi)容重疊的部分會被繪制,并覆蓋于原來內(nèi)容之上
// source-in : 新圖形只會出現(xiàn)原有內(nèi)容重疊的部分,其他區(qū)域變成透明色
// source-out : 只有新圖形中與原有的內(nèi)容不重疊的部分被保留
// destination-over : 會在原有內(nèi)容之下繪制新圖形
// destination-atop: 原有內(nèi)容中與新內(nèi)容重疊的部分會被保留,并會在原有內(nèi)容之下繪制新圖形
// destination-in : 原有內(nèi)容中與新圖形重疊的部分會被保留,其它區(qū)域都變成透明的
// destination-out : 原有內(nèi)容中與新圖形不重疊的部分會被保留。
// lighter : 兩圖形中重疊部分作加色處理。
// copy: 只有新圖形會被保留,其它都被清除掉
// xor : 重疊的部分會變成透明
//darker 兩圖形中重疊的部分作減色處理
</pre>
</div>
CSS
<style>
span {
margin: 0 20px;
border: 1px solid #CCC;
}
.active {
background-color: orange;
color: #FFF;
}
</style>
JS
var canvas = document.createElement('canvas');
canvas.width = 500;
canvas.height = 500;
document.body.appendChild(canvas);
var ctx = canvas.getContext('2d');
更改圖形重疊函數(shù)
function changeOperation(oper) {
ctx.save();
ctx.clearRect(0, 0, 500, 500);
ctx.beginPath();
ctx.fillStyle = 'green';
ctx.fillRect(180, 150, 200, 200);
ctx.globalCompositeOperation = oper || 'source-over';
ctx.beginPath();
ctx.fillStyle = 'orange';
ctx.arc(300, 300, 100, 0, 2 * Math.PI);
ctx.fill();
ctx.restore();
}
changeOperation();
綁定點(diǎn)擊切換圖形事件:
var types = document.getElementById('types');
var typeSpan = types.children;
for (var i = 0; i < typeSpan.length; i++) {
typeSpan.index = i;
}
types.onclick = function (e) {
var tar = e.target;
for (var i = 0; i < typeSpan.length; i++) {
typeSpan[i].classList.remove('active');
}
tar.classList.add('active');
changeOperation(tar.innerHTML);
}