Canvas--合成

1、globalAlpha属性:设置或返回绘图的当前透明值(alpha 或 transparency)。

  globalAlpha 属性值必须是介于 0.0(完全透明) 与 1.0(不透明) 之间的数字。

  设置后所绘制的所有图形都具有该透明度。

 1 for (let i = 0; i < 10; i++) {
 2     if (i < 5) {
 3         context.beginPath()
 4         context.globalAlpha = 1
 5         context.fillStyle = 'red'
 6         context.fillRect(0 + 200 * i, 0, 100, 80)
 7         context.closePath()
 8 
 9         context.beginPath()
10         context.fillStyle = 'blue'
11         context.globalAlpha = 0.1 * (i + 1)
12         context.fillRect(50 + 200 * i, 40, 100, 80)
13         context.closePath()
14     } else {
15         context.beginPath()
16         context.globalAlpha = 1
17         context.fillStyle = 'red'
18         context.fillRect(0 + 200 * (i - 5), 150, 100, 80)
19         context.closePath()
20 
21         context.beginPath()
22         context.fillStyle = 'blue'
23         context.globalAlpha = 0.1 * (i + 1)
24         context.fillRect(50 + 200 * (i - 5), 190, 100, 80)
25         context.closePath()
26     }
27 }

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

  属性值:

  source-over         :  默认。在目标图像上显示源图像。

  source-atop         :  在目标图像顶部显示源图像。源图像位于目标图像之外的部分是不可见的。

  source-in             :  在目标图像中显示源图像。只有目标图像之内的源图像部分会显示,目标图像是透明的。

  source-out           :  在目标图像之外显示源图像。只有目标图像之外的源图像部分会显示,目标图像是透明的。

  destination-over  :  在源图像上显示目标图像。

  destination-atop  :  在源图像顶部显示目标图像。目标图像位于源图像之外的部分是不可见的。

  destination-in      :  在源图像中显示目标图像。只有源图像之内的目标图像部分会被显示,源图像是透明的。

  destination-out    :  在源图像之外显示目标图像。只有源图像之外的目标图像部分会被显示,源图像是透明的。

  lighter                  :  显示源图像 + 目标图像。

  copy                    :  显示源图像。忽略目标图像。

  xor                       :  使用异或操作对源图像与目标图像进行组合。

 1 const GCO = ['source-over', 'source-atop', 'source-in', 'source-out', 'destination-over',
 2     'destination-atop', 'destination-in', 'destination-out', 'lighter', 'copy', 'xor'
 3 ]
 4 
 5 for (let i = 0; i < GCO.length; i++) {
 6     let div = document.createElement('div')
 7     div.style.float = 'left'
 8     let canvas = document.createElement('canvas')
 9     canvas.width = 300
10     canvas.height = 240
11     let ctx = canvas.getContext('2d')
12 
13     ctx.beginPath()
14     ctx.save()
15     ctx.fillStyle = "red";
16     ctx.fillRect(0, 0, 150, 120);
17     ctx.globalCompositeOperation = GCO[i];
18     ctx.fillStyle = "blue";
19     ctx.fillRect(75, 60, 150, 120);
20     ctx.closePath()
21 
22     ctx.restore()
23     ctx.beginPath()
24     ctx.fillStyle = '#000'
25     ctx.shadowColor = '#ffff00'
26     ctx.shadowBlur = 5
27     ctx.font = 'bold 30px Arial'
28     ctx.textAlign = 'center'
29     ctx.textBaseline = 'middle'
30     ctx.fillText(GCO[i], 150, 120)
31     ctx.closePath()
32 
33     div.appendChild(canvas)
34     document.body.appendChild(div)
35 }

posted @ 2017-11-09 16:09  穿山甲到底说了什么  阅读(234)  评论(0编辑  收藏  举报