globalAlpha = 0 【默认值为1,这个是改变透明度的 0-1】
var canvas = document.getElementById("canvas"); if(canvas.getContext){ var ctx = canvas.getContext("2d"); ctx.beginPath(); //绘制一个红色矩形 ctx.fillStyle = "red"; ctx.fillRect(20,20,80,80); //修改全局透明度 ctx.globalAlpha = 0.5; //绘制一个透明度为 0.5 的绿色矩形 ctx.fillStyle = "green"; ctx.fillRect(50,50,80,80); //修改全局透明度为1 ctx.globalAlpha = 1; //绘制一个不透明的灰色矩形 ctx.fillStyle = "grey"; ctx.fillRect(70,70,80,80); ctx.stroke(); ctx.closePath(); }
globalCompositeOperation = "" 【它的值是一个字符串】
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> .divStyle{float:left;border:1px solid red;width:220px;height:200px;margin:5px;} .pStyle{font-family:Microsoft YaHei;font-size:22px;font-weight:bold;text-indent:1em;} </style> </head> <body> <script> var glo = [ "source-over","source-in","source-out","source-atop", "destination-over","destination-in","destination-out", "destination-atop","lighter","copy","xor" ]; //遍历数组,根据不同的值绘制图像 for(i in glo){GCO(glo[i]);}; //创建、绘制 function GCO(stringTextGco){ //创建元素 var div = document.createElement("div"); var p = document.createElement("p") var canvas = document.createElement("canvas"); div.className = "divStyle"; p.className = "pStyle"; p.innerHTML = stringTextGco; canvas.width = 220; canvas.height = 150; //添加到页面 div.appendChild(p); div.appendChild(canvas); document.body.appendChild(div); //画布 if(canvas.getContext){ var ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.fillStyle = "black"; ctx.fillRect(30,0,70,70); //后绘制的图像位于先绘制的图像上方 ctx.globalCompositeOperation = stringTextGco; ctx.fillStyle = "red"; ctx.fillRect(60,30,70,70); ctx.closePath(); }; }; </script> </body> </html>
以上代码运行后效果图:(globalCompositeOperation的每个值的不同效果)