这次要讲的是控制canvas中的图形组合模式的属性:globalCompositeOperation.这个属性的名字很长,翻译过来大概是”全局组合操作”的意思.
ctx.globalCompositeOperation = type;
他的作用呢有些像photoshop中的图层叠加效果,比如加亮变暗叠加.如果你没学过作图,可能这些术语听起来很抽象,不过不要紧,因为这个属性我们基本上不用.
为什么不用?还是这个原因:标准不一.设置同样的globalCompositeOperation,在chrome与firefox中会出现截然不同的效果,甚至同为webkit内核的浏览器safari和chrome也不能做到效果统一.
更离谱的是,w3c通常是作为标准的制订者出现,他们也制订了globalCompositeOperation的标准,就是firefox中用的这种,但他们又貌似觉得chrome的做法才是更合理的,所以有传言globalCompositeOperation的标准将会更改—-这样一来,我们可以在很长一段时间内不考虑使用globalCompositeOperation属性了.
如果依照firefox(即现行标准)的做法,globalCompositeOperation的属性有以下效果(直接摘自MDN):
注意:下面所有例子中,蓝色方块是先绘制的,即“已有的 canvas 内容”,红色圆形是后面绘制,即“新图形”。
source-over (default)
This is the default setting and draws new shapes on top of the existing canvas content.这是默认设置,新图形会覆盖在原有内容之上。
destination-over
New shapes are drawn behind the existing canvas content.会在原有内容之下绘制新图形。
source-in
The new shape is drawn only where both the new shape and the destination canvas overlap. Everything else is made transparent新图形会仅仅出现与原有内容重叠的部分。其它区域都变成透明的。
destination-in
The existing canvas content is kept where both the new shape and existing canvas content overlap. Everything else is made transparent.原有内容中与新图形重叠的部分会被保留,其它区域都变成透明的。
source-out
The new shape is drawn where it doesn’t overlap the existing canvas content.结果是只有新图形中与原有内容不重叠的部分会被绘制出来。
destination-out
The existing content is kept where it doesn’t overlap the new shape.原有内容中与新图形不重叠的部分会被保留。
source-atop
The new shape is only drawn where it overlaps the existing canvas content.新图形中与原有内容重叠的部分会被绘制,并覆盖于原有内容之上。
destination-atop
The existing canvas is only kept where it overlaps the new shape. The new shape is drawn behind the canvas content.原有内容中与新内容重叠的部分会被保留,并会在原有内容之下绘制新图形
lighter
Where both shapes overlap the color is determined by adding color values.两图形中重叠部分作加色处理。
darker
Where both shapes overlap the color is determined by subtracting color values.两图形中重叠的部分作减色处理。
xor
Shapes are made transparent where both overlap and drawn normal everywhere else.重叠的部分会变成透明。
copy
Only draws the new shape and removes everything else.只有新图形会被保留,其它都被清除掉。
而这篇文章则列举了这些属性在不同浏览器下的奇异表现:http://elementstorm.iteye.com/blog/757605
globalCompositeOperation虽然名字很长很强大,但由于他自己都不知道该按什么标准渲染,也就让有心使用者没有那个胆量去尝试.现阶段大家只需要了解即可.
canvas本身就还是不门不太成熟的技术,只有在使用中不停的完善,才能获得稳定的受众.
至此,关于canvas的基本知识点,也就基本讲完了.在此过程中为发现,canvas的缺陷还很多,而各个浏览器在这节骨眼上还闹独立,导致标准的制订依然拖延中;canvas的效率毫无亮点,基本与制作中型游戏无缘了.
不过,个人认为web本来就不是用来体验游戏快感的,web在于便利的分享,交互,有了canvas等新元素的加入,web也起码能变得故生动吧.