Please note, this is a STATIC archive of website developer.mozilla.org from November 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

组合 Compositing

In all of our previous examples, shapes were always drawn one on top of the other. This is more than adequate for most situations. This, for instance, limits in what order composite shapes are built up. We can however change this behaviour by setting the globalCompositeOperation property.

之前的例子里面,我们总是将一个图形画在另一个之上,大多数情况下,这样是不够的。比如说,它这样受制于图形的绘制顺序。不过,我们可以利用 globalCompositeOperation 属性来改变这些做法。

globalCompositeOperation

We can not only draw new shapes behind existing shapes but we can also use it to mask off certain areas, clear sections from the canvas (not limited to rectangles like the clearRect method does) and more.

我们不仅可以在已有图形后面再画新图形,还可以用来遮盖,清除(比 clearRect 方法强劲得多)某些区域。

globalCompositeOperation = type

type is a string representing any one of twelve compositing operations. Each of the available types is described below.

type 是下面 12 种字符串值之一:

Note: In all of the examples below the blue square is drawn first and referred to as 'existing canvas content'. The red circle is drawn second and referred to as 'new shape'.

注意:下面所有例子中,蓝色方块是先绘制的,即“已有的 canvas 内容”,红色圆形是后面绘制,即“新图形”。

source-over (default)
This is the default setting and draws new shapes on top of the existing canvas content.

这是默认设置,新图形会覆盖在原有内容之上。

Image:Canvas_composite_srcovr.png

destination-over
New shapes are drawn behind the existing canvas content.

会在原有内容之下绘制新图形。

Image:Canvas_composite_destovr.png

source-in
The new shape is drawn only where both the new shape and the destination canvas overlap. Everything else is made transparent

新图形会仅仅出现与原有内容重叠的部分。其它区域都变成透明的。

Image:Canvas_composite_srcin.png

destination-in
The existing canvas content is kept where both the new shape and existing canvas content overlap. Everything else is made transparent.

原有内容中与新图形重叠的部分会被保留,其它区域都变成透明的。

Image:Canvas_composite_destin.png

source-out
The new shape is drawn where it doesn't overlap the existing canvas content.

结果是只有新图形中与原有内容不重叠的部分会被绘制出来。

Image:Canvas_composite_srcout.png

destination-out
The existing content is kept where it doesn't overlap the new shape.

原有内容中与新图形不重叠的部分会被保留。

Image:Canvas_composite_destout.png

source-atop
The new shape is only drawn where it overlaps the existing canvas content.

新图形中与原有内容重叠的部分会被绘制,并覆盖于原有内容之上。

Image:Canvas_composite_srcatop.png

destination-atop
The existing canvas is only kept where it overlaps the new shape. The new shape is drawn behind the canvas content.

原有内容中与新内容重叠的部分会被保留,并会在原有内容之下绘制新图形

Image:Canvas_composite_destatop.png

lighter
Where both shapes overlap the color is determined by adding color values.

两图形中重叠部分作加色处理。

Image:Canvas_composite_lighten.png

darker
Where both shapes overlap the color is determined by subtracting color values.

两图形中重叠的部分作减色处理。

Image:Canvas_composite_darken.png

xor
Shapes are made transparent where both overlap and drawn normal everywhere else.

重叠的部分会变成透明。

Image:Canvas_composite_xor.png

copy
Only draws the new shape and removes everything else.

只有新图形会被保留,其它都被清除掉。

Image:Canvas_composite_copy.png

Note: Currently the copy and darker settings don't do anything in the Gecko 1.8 based browsers (Firefox 1.5 betas, etc).

注意:copydarker 属性值在 Gecko 1.8 型的浏览器(Firefox 1.5 betas,等等)上暂时还无效。

查看所有示例

裁切路径 Clipping paths

A clipping path is like a normal canvas shape but it acts as a mask to hide unwanted parts of shapes. This is visualized in the image on the right. The red star shape is our clipping path. Everything that falls outside of this path won't get drawn on the canvas.

裁切路径和普通的 canvas 图形差不多,不同的是它的作用是遮罩,用来隐藏没有遮罩的部分。如右图所示。红边五角星就是裁切路径,所有在路径以外的部分都不会在 canvas 上绘制出来。

If we compare clipping paths to the globalCompositeOperation property we've seen above; settings that achieve more or less the same effect are source-in and source-atop. The most important differences between the two are that clipping paths are never actually drawn to the canvas and the clipping path is never affected by adding new shapes. This makes clipping paths ideal for drawing multiple shapes in a restricted area.

如果和上面介绍的 globalCompositeOperation 属性作一比较,它可以实现与 source-in 和 source-atop 差不多的效果。最重要的区别是裁切路径不会在 canvas 上绘制东西,而且它永远不受新图形的影响。这些特性使得它在特定区域里绘制图形时相当好用。

In the chapter about Drawing shapes I only mentioned the stroke and fill methods, but there's a third method we can use with paths, called clip.

绘制图形 一章中,我只介绍了 strokefill 方法,这里介绍第三个方法 clip

clip()

We use the clip method to create a new clipping path. By default the canvas element has a clipping path that's the exact same size as the canvas itself (i.e. no clipping occurs).

我们用 clip 方法来创建一个新的裁切路径。默认情况下,canvas 有一个与它自身一样大的裁切路径(也就是没有裁切效果)。

clip 的例子

In this example I'll be using a circular clipping path to restrict the drawing of a set of random stars to a particular region.

这个例子,我会用一个圆形的裁切路径来限制随机星星的绘制区域。

In the first few lines of code I draw a black rectangle the size of the canvas as a backdrop and translate the origin to the center. Below this I create the circular clipping path by drawing an arc. By calling the clip method the clipping path is created. Clipping paths are also part of the canvas save state. If we wanted to keep the original clipping path we could have saved the canvas state before creating the new one.

首先,我画了一个与 canvas 一样大小的黑色方形作为背景,然后移动原点至中心点。然后用 clip 方法创建一个弧形的裁切路径。裁切路径也属于 canvas 状态的一部分,可以被保存起来。如果我们在创建新裁切路径时想保留原来的裁切路径,我们需要做的就是保存一下 canvas 的状态。

Everything that's drawn after creating the clipping path will only appear inside that path. You can see this clearly in the linear gradient that's drawn next. After this a set of 50 randomly positioned and scaled stars is drawn (I'm using a custom function for this). Again the stars only appear inside the defined clipping path.

裁切路径创建之后所有出现在它里面的东西才会画出来。在画线性渐变时这个就更加明显了。然后在随机位置绘制 50 大小不一(经过缩放)的颗,当然也只有在裁切路径里面的星星才会绘制出来。

查看示例

function draw() {
  var ctx = document.getElementById('canvas').getContext('2d');
  ctx.fillRect(0,0,150,150);
  ctx.translate(75,75);

  // Create a circular clipping path
  ctx.beginPath();
  ctx.arc(0,0,60,0,Math.PI*2,true);
  ctx.clip();

  // draw background
  var lingrad = ctx.createLinearGradient(0,-75,0,75);
  lingrad.addColorStop(0, '#232256');
  lingrad.addColorStop(1, '#143778');
  
  ctx.fillStyle = lingrad;
  ctx.fillRect(-75,-75,150,150);

  // draw stars
  for (var j=1;j<50;j++){
    ctx.save();
    ctx.fillStyle = '#fff';
    ctx.translate(75-Math.floor(Math.random()*150),
                  75-Math.floor(Math.random()*150));
    drawStar(ctx,Math.floor(Math.random()*4)+2);
    ctx.restore();
  }
  
}
function drawStar(ctx,r){
  ctx.save();
  ctx.beginPath()
  ctx.moveTo(r,0);
  for (var i=0;i<9;i++){
    ctx.rotate(Math.PI/5);
    if(i%2 == 0) {
      ctx.lineTo((r/0.525731)*0.200811,0);
    } else {
      ctx.lineTo(r,0);
    }
  }
  ctx.closePath();
  ctx.fill();
  ctx.restore();
}

文档标签和贡献者

标签: 
 此页面的贡献者: fscholz, ziyunfei, zhongsheng, leegorous
 最后编辑者: fscholz,