【canvas學習筆記七】混合和裁剪

globalCompositeOperation

若是咱們先畫了一個圖形,而後要在這個圖形上面再畫一個圖形,那麼這個圖形會怎麼樣呢?是覆蓋在原來的圖形上面嗎?這時候,就要用到globalCompositeOperation這個屬性了。
當有兩個圖形重疊的時候,能夠有不少種混合模式,好比上面的圖形蓋住下面的,或者下面的圖形蓋住上面的,或者去掉重疊的部分。globalCompositeOperation這個屬性就是用來設置混合方式的。這個屬性總共有12種值。
由於太多了,我就不一一列舉了,你們本身去查。戳這裏javascript

我這裏就簡單介紹其中幾種。java

source-over
默認值。新的形狀會覆蓋在原來的形狀上。
destination-over
和上面一個屬性反過來。
copy
只顯示新形狀。canvas

這個屬性和PhotoShop圖層裏的混合模式是同樣的,也有正片疊底、亮化、差值等等模式。dom

裁剪

若是你只想在一個圓形區域畫圖,而圓形區域外的圖形都看不見的話,你能夠使用clip()裁剪畫布。
imagerest

實際上canvas自己就帶有一個canvas同樣大的裁剪區域,因此實際上並無添加裁剪路徑,只是裁剪路徑被修改了。
使用clip()無需用closePath()閉合路徑,clip()自己就會閉合路徑。
須要注意的是,當clip()了一個路徑之後,沒法改變clip()的路徑形狀,要恢復的話只能用restore()回到原先的狀態。code

例子

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

相關文章
相關標籤/搜索