Canvas 图像混排模式
上一章节中我们使用 ctx.globalCompositeOperation=xor
属性演示了如何去掉两个图形的重叠部分
本章节我们把所有的图形混排模式一并用一个范例演示出来
我们会使用上图这种绘制模式,首先绘制一个蓝色的矩形,然后绘制一个红色矩形和它重叠,看看不同的图形混排模式带来的效果
所有代码如下
<!DOCTYPE html> <meta charset="utf-8"> <div style="border:1px solid #ccc"> <canvas id="canvas-1" width="500" height="200"> </canvas> </div> <script> var gco = [ 'source-over','source-in','source-out','source-atop', 'destination-over','destination-in','destination-out','destination-atop', 'lighter', 'copy','xor', 'multiply', 'screen', 'overlay', 'darken', 'lighten', 'color-dodge', 'color-burn', 'hard-light', 'soft-light', 'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity' ]; var canvas = document.getElementById("canvas-1"); canvas.width = 500; canvas.height = 2700; var ctx = canvas.getContext("2d"); function draw() { for (var i = 0; i < gco.length; i++ ) { ctx.font = "16px Microsoft YaHei" ctx.textBaseline = "middle"; ctx.fillStyle="#333" ctx.save(); ctx.fillText(gco[i],10,15); ctx.fillStyle = "blue"; ctx.fillRect(10, 35, 50, 50); ctx.translate(70,0) ctx.fillStyle = "blue"; ctx.fillRect(10, 35, 50, 50); ctx.fillStyle = "red"; ctx.fillRect(25, 50, 50, 50); var canvas2 = document.createElement("canvas"); ctx2 = canvas2.getContext("2d"); ctx2.fillStyle = "blue"; ctx2.fillRect(10, 35, 50, 50); ctx2.globalCompositeOperation = gco[i]; ctx2.fillStyle = "red"; ctx2.fillRect(25, 50, 50, 50); ctx2.globalCompositeOperation = "source-over"; ctx.drawImage(canvas2,85,0); ctx.restore(); ctx.translate(0,100); } } draw(); </script>
运行结果如下