CANVAS - globalCompositeOperation

by Boban Stojanovski

CSS

canvas {
    border: 1px solid #d3d3d3;
    margin-right: 10px;
    margin-bottom: 20px;
}

JavaScript

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");

var n;
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 = "rgba(0, 0, 255, 0.5)";
    //ctx.fillStyle = "blue";
    ctx.fillRect(10, 10, 50, 50);
    ctx.globalCompositeOperation = gco[n];
    
    ctx.beginPath();   
	ctx.fillStyle = "rgba(255, 0, 0, 0.5)";
 	//ctx.fillStyle = "red";
    ctx.arc(50, 50, 30, 0, 2 * Math.PI);
    ctx.fill();
    document.write("</div>");
}