globalCompositeOperation 屬性設(shè)置要在繪制新形狀時應(yīng)用的合成操作的類型,其中type是用于標識要使用的合成或混合模式操作的字符串。
使用不同的 globalCompositeOperation 值繪制矩形。紅色矩形是目標圖像,藍色矩形是源圖像:
JavaScript:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML canvas globalCompositeOperation屬性使用-菜鳥教程(cainiaoplus.com)</title>
</head>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
您的瀏覽器不支持 HTML5 canvas 標簽。
</canvas>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle="red";
ctx.fillRect(20,20,75,50);
ctx.fillStyle="blue";
ctx.globalCompositeOperation="source-over";
ctx.fillRect(50,50,75,50);
ctx.fillStyle="red";
ctx.fillRect(150,20,75,50);
ctx.fillStyle="blue";
ctx.globalCompositeOperation="destination-over";
ctx.fillRect(180,50,75,50);
</script>
</body>
</html>測試看看 ?/?IEFirefoxOperaChromeSafari
Internet Explorer 9、Firefox、Opera、Chrome 和 Safari 支持 globalCompositeOperation 屬性。
注意:Internet Explorer 8 及之前的版本不支持 <canvas> 元素。
globalCompositeOperation 屬性設(shè)置或返回如何將一個源(新的)圖像繪制到目標(已有的)的圖像上。
源圖像 = 您打算放置到畫布上的繪圖。
目標圖像 = 您已經(jīng)放置在畫布上的繪圖。
| 默認值: | source-over |
|---|---|
| JavaScript 語法: | context.globalCompositeOperation="source-in"; |
| 值 | 描述 |
|---|---|
| source-over | 默認。在目標圖像上顯示源圖像。 |
| source-atop | 在目標圖像頂部顯示源圖像。源圖像位于目標圖像之外的部分是不可見的。 |
| source-in | 在目標圖像中顯示源圖像。只有目標圖像之內(nèi)的源圖像部分會顯示,目標圖像是透明的。 |
| source-out | 在目標圖像之外顯示源圖像。只有目標圖像之外的源圖像部分會顯示,目標圖像是透明的。 |
| destination-over | 在源圖像上顯示目標圖像。 |
| destination-atop | 在源圖像頂部顯示目標圖像。目標圖像位于源圖像之外的部分是不可見的。 |
| destination-in | 在源圖像中顯示目標圖像。只有源圖像之內(nèi)的目標圖像部分會被顯示,源圖像是透明的。 |
| destination-out | 在源圖像之外顯示目標圖像。只有源圖像之外的目標圖像部分會被顯示,源圖像是透明的。 |
| lighter | 顯示源圖像 + 目標圖像。 |
| copy | 顯示源圖像。忽略目標圖像。 |
| xor | 使用異或操作對源圖像與目標圖像進行組合。 |
所有 globalCompositeOperation 屬性值:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML canvas globalCompositeOperation屬性使用-菜鳥教程(cainiaoplus.com)</title>
<style>
canvas
{
border:1px solid #d3d3d3;
margin-right:10px;
margin-bottom:20px;
}
</style>
</head>
<body>
<script>
var gco=new Array();
gco.push("source-atop");
gco.push("source-in");
gco.push("source-out");
gco.push("source-over");
gco.push("destination-atop");
gco.push("destination-in");
gco.push("destination-out");
gco.push("destination-over");
gco.push("lighter");
gco.push("copy");
gco.push("xor");
for (n=0;n<gco.length;n++)
{
document.write("<div id='p_" + n + "' style='float:left;'>" + gco[n] + ":<br>");
var c=document.createElement("canvas");
c.width=120;
c.height=100;
document.getElementById("p_" + n).appendChild(c);
var ctx=c.getContext("2d");
ctx.fillStyle="blue";
ctx.fillRect(10,10,50,50);
ctx.globalCompositeOperation=gco[n];
ctx.beginPath();
ctx.fillStyle="red";
ctx.arc(50,50,30,0,2*Math.PI);
ctx.fill();
document.write("</div>");
}
</script>
</body>
</html>測試看看 ?/?