【canvas学习笔记七】混合和裁剪

globalCompositeOperation

如果我们先画了一个图形,然后要在这个图形上面再画一个图形,那么这个图形会怎么样呢?是覆盖在原来的图形上面吗?这时候,就要用到globalCompositeOperation这个属性了。
当有两个图形重叠的时候,可以有很多种混合模式,比如上面的图形盖住下面的,或者下面的图形盖住上面的,或者去掉重叠的部分。globalCompositeOperation这个属性就是用来设置混合方式的。这个属性总共有12种值。
因为太多了,我就不一一列举了,大家自己去查。戳这里

我这里就简单介绍其中几种。

source-over
默认值。新的形状会覆盖在原来的形状上。
destination-over
和上面一个属性反过来。
copy
只显示新形状。

这个属性和PhotoShop图层里的混合模式是一样的,也有正片叠底、亮化、差值等等模式。

裁剪

如果你只想在一个圆形区域画图,而圆形区域外的图形都看不见的话,你可以使用clip()裁剪画布。
image

实际上canvas本身就带有一个canvas一样大的裁剪区域,所以实际上并没有添加裁剪路径,只是裁剪路径被修改了。
使用clip()无需用closePath()闭合路径,clip()本身就会闭合路径。
需要注意的是,当clip()了一个路径以后,无法改变clip()的路径形状,要恢复的话只能用restore()回到原先的状态。

例子

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();
}

结果

image

原文地址:https://www.cnblogs.com/-867259206/p/7444805.html