Canvasにテキストを描画します。フォントや色なども自由に指定できます。
テキストを描く
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 | 筆記体 |
もちろん特定のフォントを決め打ちすることもできますが、ユーザーの環境によってはインストールされていない場合があることを考慮する必要があります。
どうしても特定のスタイルで表示したい場合は画像にして貼り付けるのが安全です。
参考ページ
- https://developer.mozilla.org/ja/docs/Drawing_text_using_a_canvas
- https://developer.mozilla.org/ja/docs/Web/Guide/HTML/Canvas_tutorial/Applying_styles_and_colors
- https://developer.mozilla.org/ja/docs/Web/CSS/font-family
このブログを応援する
お寄せいただいたお気持ちは全額サーバ代や次の記事を執筆するための原資として活用させていただいております。この記事が参考になった場合などぜひご検討ください。