GlobalCompositeOperation | HTML<canvas>属性

定义与用法

globalCompositeOperation 属性设置或返回如何将一个源(新的)图像绘制到目标(已有的)的图像上。

源图像 = 您打算放置到画布上的绘图。

目标图像 = 您已经放置在画布上的绘图。


语法格式

context.globalCompositeOperation=”source-in”;

默认值:source-over


示例代码

使用不同的 globalCompositeOperation 值绘制矩形。红色矩形是目标图像,蓝色矩形是源图像

<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>

效果展示:

source-over
destination-over
 
您的浏览器不支持 HTML5 canvas 标签。

亲自试试


浏览器支持

属性
GlobalCompositeOperationYesYesYesYesYes

Internet Explorer 9、Firefox、Opera、Chrome 和 Safari 支持 globalCompositeOperation 属性。

提示:Internet Explorer 8 及之前的版本不支持 <canvas> 元素。


属性值

描述
source-over默认。在目标图像上显示源图像
source-atop目标图像顶部显示源图像源图像位于目标图像之外的部分是不可见的。
source-in目标图像中显示源图像。只有目标图像之内的源图像部分会显示,目标图像是透明的。
source-out目标图像之外显示源图像。只有目标图像之外的源图像部分会显示,目标图像是透明的。
destination-over源图像上显示目标图像
destination-atop源图像顶部显示目标图像目标图像位于源图像之外的部分是不可见的。
destination-in源图像中显示目标图像。只有源图像之内的目标图像部分会被显示,源图像是透明的。
destination-out源图像之外显示目标图像。只有源图像之外的目标图像部分会被显示,源图像是透明的。
lighter显示源图像 + 目标图像
copy显示源图像。忽略目标图像
xor使用异或操作对源图像目标图像进行组合。

示例代码

<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");
    document.write("<div style='display:inline-block;width:quto;height:auto;'>");
    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>");
    }
    document.write("</div>");
</script>

亲自试试


相关