0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Canvas の選択範囲を getImageData の前に切り詰める

0
Posted at

ドラッグで画像を選択すると、終点が Canvas の外に出ることがあります。範囲外を含む矩形を getImageData() に渡すと、外側の画素は透明になります。Canvas に重なる部分だけが必要なら、先に矩形の境界を Canvas の端に収めます。

始点と終点は Canvas のピクセル座標に変換済みとします。各軸で小さい方を切り下げ、大きい方を切り上げます。そのあとで左右を幅の範囲に、上下を高さの範囲に収めます。選択に面積がない場合や Canvas と重ならない場合は null を返します。

function readSelection(canvas, ctx, start, end) {
  if (start.x === end.x || start.y === end.y) return null;

  const clamp = (n, max) => Math.min(Math.max(n, 0), max);
  const left = clamp(Math.floor(Math.min(start.x, end.x)), canvas.width);
  const top = clamp(Math.floor(Math.min(start.y, end.y)), canvas.height);
  const right = clamp(Math.ceil(Math.max(start.x, end.x)), canvas.width);
  const bottom = clamp(Math.ceil(Math.max(start.y, end.y)), canvas.height);
  if (right <= left || bottom <= top) return null;

  return ctx.getImageData(left, top, right - left, bottom - top);
}

幅と高さが 10 の Canvas で (8.5, 6.2) から (-2.2, 14.1) へドラッグすると、getImageData(0, 6, 9, 4) を呼びます。両方の x 座標が右端より外なら、左右の境界が同じ位置になるため読み出しません。

参照仕様は WHATWG HTML Living Standard の Canvas 2D Context、Pixel manipulation 節です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?