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?

drawImage() の負の幅だけでは画像は反転しない

0
Posted at

drawImage() の幅に負の値を渡しても、画素の並びは反転しません。MDN は、負の幅では矩形が反対方向へ広がり、画像そのものは反転しないと説明しています。

左右反転には座標変換を使います。次の例では、読み込み済みの画像をキャンバス全体へ描きます。

function drawMirrored(ctx, img) {
  const { width, height } = ctx.canvas;
  ctx.save();
  ctx.translate(width, 0);
  ctx.scale(-1, 1);
  ctx.drawImage(img, 0, 0, width, height);
  ctx.restore();
}

この例は、呼び出し前の変換行列が単位行列であり、キャンバスの幅と高さが正であることを前提にしています。画像とキャンバスの縦横比が異なると、画像は引き伸ばされます。縦横比を保つ処理は別途必要です。

確認用の画像には左右で異なる文字や目印を入れると、反転したかを見分けやすくなります。左右対称の写真だけでは、変換の間違いを見落とすことがあります。

私は画像変換サービス Morphio に関わっています。コード例では、反転と拡大縮小を分けて確認しています。

参考: MDN drawImage()

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?