【JavaScript】Canvasで消しゴム機能を白色ではなく、透明にする方法

JavaScript

はじめに

canvas.toDataURLで画像を保存する際、png形式だと背景が透明になります。

消しゴム機能をstrokeStyle白色で実装すると、保存する時に白線が残るため、消しゴム機能を透明にしたかった。

透明にする方法

結論

CanvasRenderingContext2D.globalCompositeOperation = ‘destination-out’を使用する。

CanvasRenderingContext2D.globalCompositeOperation

CanvasRenderingContext2D.globalCompositeOperationは適合する合成処理の種類を定めるプロパティです。

デフォルトの設定はsource-overで新たな図形をすでにあるCanvasの内容の上に描きます。

destination-outは新しい図形と重なった部分が透明になります。

詳細説明
https://developer.mozilla.org/ja/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation

実装してみる

<canvas class="drawPicture" id="js-drawPicture" width="600" height="400"></canvas>

<button class="eraser" id="js-eraser">消しゴムモード</button>
let canvas = document.getElementById('js-drawPicture');
let ctx = canvas.getContext('2d');
const elaser = document.getElementById('js-eraser');
let object = { handleEvent: DrawWithMause };
let drawMode = 1;  // 1:消しゴムモード、2:描写モード
let clickFlag = 0; // クリック判定 0:クリック終了、1:クリック開始、2:クリック中

// クリック長押しで線を描く処理
canvas.addEventListener('mousedown',drawStart);
canvas.addEventListener('mouseout', drawEnd);
canvas.addEventListener('mouseup', drawEnd);

function draw(x,y) {
  drawJudgement = 1;
  if (clickFlag === 1) {
    clickFlag = 2;
    ctx.beginPath();
    ctx.moveTo(x,y);
  } else {
    ctx.lineTo(x,y);
  }
    ctx.stroke();
  }

function drawStart() {
  clickFlag = 1;
  canvas.addEventListener('mousemove', object);
}

function drawEnd() {
  clickFlag = 0;
  ctx.closePath();
  canvas.removeEventListener('mousemove', object);
}

function DrawWithMause(event) {
  let rect = event.currentTarget.getBoundingClientRect();
  x = event.clientX - rect.left;
  y = event.clientY - rect.top;
  draw(x,y);
}

// 消しゴムと描写モードを切り替え
elaser.addEventListener('click', changeDrawMode);

function changeDrawMode() {
  if (drawMode === 1) {
    drawMode = 2;
    // 線を描くとその範囲が透明になる設定
    ctx.globalCompositeOperation = 'destination-out';
    elaser.textContent  = '描画モード'
  } else {
    // デフォルトの設定に戻す
    ctx.globalCompositeOperation = 'source-over';
    drawMode = 1;
    ctx.strokeStyle = lineColor;
    elaser.textContent = '消しゴムモード';
  }
}

実装したアプリ

上記のコードを記載したお絵かきアプリを作ってみた

Application Error

まとめ

CanvasRenderingContext2D.globalCompositeOperation = ‘destination-out’は重なった図形の範囲を透明にできるので、透明にする消しゴム機能を実装できる。

CanvasRenderingContext2D.globalCompositeOperationでさまざまな合成処理を設定できる。

コメント

タイトルとURLをコピーしました