[HTML5] Canvasにテキストを描く

  • このエントリーをはてなブックマークに追加
  • LINEで送る
この記事は 2019年9月2日 に書かれたものです

Canvasにテキストを描画します。フォントや色なども自由に指定できます。

- Sponsored Link -

テキストを描く

fillText編

ctx.fillText()でテキストをCanvasに描画します。

ctx.fillText(text, x, y)

text
描画したい文字列
x, y
描画したいCanvasの座標。Canvasの左上を(0, 0)がとなります。
<canvas id="board" width="350" height="150"></canvas>

<script>
window.onload = ()=>{
  const board = document.querySelector("#board");
  const ctx = board.getContext("2d");

  ctx.font = "48px serif";
  ctx.fillText("Hello world", 10, 50);
};
</script>

実行例

strokeText編

ctx.strokeText()はテキストの輪郭を描画します。引数はctx.fillText()と同じです。

ctx.strokeText(text, x, y)

text
描画したい文字列
x, y
描画したいCanvasの座標。Canvasの左上を(0, 0)がとなります。
<canvas id="board" width="350" height="150"></canvas>

<script>
window.onload = ()=>{
  const board = document.querySelector("#board");
  const ctx = board.getContext("2d");

  ctx.font = "48px serif";
  ctx.strokeText("Hello world", 10, 50);
};
</script>

実行例

スタイルを設定する

色をつける

最終的に塗りつぶす場合の色はctx.fillStyle、輪郭を描画する場合はctx.strokeStyleで指定できます。両方ともプロパティですので右辺に色を記述します。

<canvas id="board" width="350" height="150"></canvas>

<script>
window.onload = ()=>{
  const board = document.querySelector("#board");
  const ctx = board.getContext("2d");
  // 共通
  ctx.font = "48px serif";

  // 塗りつぶし
  ctx.fillStyle = "Red";
  ctx.fillText("Hello world", 10, 50);

  // 輪郭
  ctx.strokeStyle = "Blue";
  ctx.strokeText("Hello world", 10, 110);
};
</script>

実行例

色の指定方法はCSSと同様です。

ctx.fillStyle = "orange";
ctx.fillStyle = "#FFA500";
ctx.fillStyle = "rgb(255, 165, 0)";
ctx.fillStyle = "rgba(255, 165, 0, 1)";

mdnより

文字サイズとフォント

すでにサンプルに登場していますが、ctx.fontで指定します。プロパティですので右辺にフォントや文字サイズを書きます。

<canvas id="board" width="400" height="350"></canvas>

<script>
window.onload = ()=>{
  const board = document.querySelector("#board");
  const ctx = board.getContext("2d");
  ctx.fillStyle = "Black";

  let y = 50;
  ["sans-serif", "serif", "monospace", "fantasy", "cursive"].forEach( (font) =>{
    ctx.font = `32px ${font}`;
    ctx.fillText(`Hello world (${font})`, 10, y);
    y += 60;
  });
};
</script>

実行例

フォントの指定方法はCSSと同様で、定義済みのフォントファミリーは以下です。

定義済み説明
sans-serifゴシック
serif明朝体
monospace等幅
fantasy装飾
cursive筆記体

もちろん特定のフォントを決め打ちすることもできますが、ユーザーの環境によってはインストールされていない場合があることを考慮する必要があります。

どうしても特定のスタイルで表示したい場合は画像にして貼り付けるのが安全です。

参考ページ

コメント

コメント欄は休止中です。お問い合わせはこちらからどうぞ。ご質問はTwitterにリプを投げてください。

このブログを応援する

お寄せいただいたお気持ちは全額サーバ代や次の記事を執筆するための原資として活用させていただいております。この記事が参考になった場合などぜひご検討ください。

PayPal(ペイパル)
PayPalで300円支払う
※金額は任意で変更できます。
※100円でも泣いて喜びますw
※住所の入力欄が現れた場合は「no needed」を選択ください
これまでのご協力者さま
- Sponsored Link -