今回は、合成とクリッピングについて見ていきます。
図形の合成は沢山のパターンがあるので、実際にコードを書いて確認しておきましょう。
globalCompositeOperation
「globalCompositeOperation」は図形を合成するプロパティになります。
合成する時は以下の種類を設定します。
- source-over
- source-in
- source-out
- source-atop
- destination-over
- destination-in
- destination-out
- destination-atop
- lighter
- copy
- xor
- multipiy
- screen
- overlay
- darken
- lighten
- color-dodge
- color-burn
- hard-light
- soft-light
- difference
- exclusion
- hue
- saturation
- color
- luminosity
それぞれの特徴は、MDNのページでご確認ください。
const canvas33 = document.getElementById('sample33').getContext('2d');
canvas33.globalCompositeOperation = 'xor';
canvas33.fillStyle = 'green';
canvas33.fillRect(10, 10, 100, 100);
canvas33.fillStyle = 'red';
canvas33.fillRect(50, 50, 100, 100);
clip()
クリッピングパスを作成するには、「clip()」メソッドを使用します。
const canvas35 = document.getElementById('sample35');
const ctx = canvas35.getContext('2d');
// クリッピングする範囲を指定します。
ctx.beginPath();
ctx.arc(100, 75, 50, 0, Math.PI * 2);
ctx.clip();
// canvasをグリーンで塗りつぶして、0,0から100,100の矩形をオレンジで描画しています。
ctx.fillStyle = 'green';
ctx.fillRect(0, 0, canvas35.width, canvas35.height);
ctx.fillStyle = 'orange';
ctx.fillRect(0, 0, 100, 100);
const canvas36 = document.getElementById('sample36');
const ctx36 = canvas36.getContext('2d');
let clipPath = new Path2D();
clipPath.rect(80, 10, 30, 130);
clipPath.rect(40, 50, 110, 50);
ctx36.clip(clipPath, 'evenodd');
ctx36.fillStyle = 'green';
ctx36.fillRect(0, 0, canvas36.width, canvas36.height);
「Path2D」を使って記述しています。
「clip(path, fillRule)」の構文を使用しています。
パラメーターのpathは2Dのことになり、「fillRule」はポイントがクリッピング領域の内側にあるか外側にあるかを判断するためのアルゴリズムになります。
指定出来る値は、「nonzero(デフォルト)」か「evenodd」になります。
値を変えてどのようの表示されるか確認しておきましょう。
あとがき
今回の内容もMDNの内容をもとに記述していますので、合わせて以下のサイトを確認しておくとより理解が深まります。
MDN:合成とクリッピング
今回も最後までお読み頂きありがとうございました。


