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 の影の設定を次の描画へ持ち越さない

0
Posted at

Canvas 2D の shadowColor や shadowBlur は描画状態に残る。影付きの注釈の後に別の画像を描く場合は、影の設定を使う処理を save() と restore() で囲む。

function drawLabel(ctx, text, x, y) {
  ctx.save();
  try {
    ctx.shadowColor = "rgba(0, 0, 0, 0.5)";
    ctx.shadowBlur = 4;
    ctx.shadowOffsetX = 2;
    ctx.shadowOffsetY = 2;
    ctx.fillText(text, x, y);
  } finally {
    ctx.restore();
  }
}

この例は取得済みの 2D コンテキストを受け取り、文字を同期的に描く。フォントと fillStyle は呼び出す前に設定しておく。

MDN の save() の説明には、影の各属性も保存対象として載っている。restore() は保存時の値へ戻すので、必ず影が無効になるわけではない。呼び出し前に影が設定されていれば、その状態に戻る。

restore() を呼んでも、描き終わった影の画素は残る。出力を直す場合は必要な素材から描き直す。

私は画像変換プロジェクト Morphio に携わっている。このコードは描画状態を管理する例であり、製品の実装を示すものではない。

参考: MDN save()

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?