JavaScriptでcanvasにテキストを描画するプログラムを解説

JavaScriptでcanvasタグへテキストを描画するプログラミングを解説します。今回のプログラミングにおいて「canvasチュートリアル」を参考に実装しました。
canvasへ図形を描画する「JavaScriptでcanvasに図形を描画するプログラミングを解説」もぜひご覧ください。
Contents
JavaScriptでcanvasにテキストを描画するプログラミングのサンプルコード
JavaScriptでcanvasタグへテキストを描画するプログラミングコードのサンプルコードです。
<html>
<head>
<meta charset="utf-8">
<title>Canvas Text Sample</title>
</head>
<body>
<h1>Canvas Text Sample</h1>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.font = "30px serif";
ctx.fillStyle = "blue";
ctx.fillText('Canvas', 10, 30);
ctx.font = "30px 'MS ゴシック'";
ctx.strokeStyle = "green";
ctx.strokeText('Text', 10 + (30/2 * (6 + 1)), 30 + 30);
ctx.font = "30px serif";
ctx.fillStyle = "red";
ctx.fillText('Sample', 10 + (30/2 * (6 + 1)) + (30/2 * (4 + 1)), 30 + 30 + 30);
}
</script>
</body>
</html>
JavaScriptでcanvasにテキストを描画するプログラミングを解説
JavaScriptでcanvasタグへテキストを描画するプログラミングの解説です。
HTML部分
HTML部分の解説です。
文字コードを指定
HTMLのheadタグ内にmetaタグでcharset(文字コード)をUTF-8に指定します。
<meta charset="utf-8">
Webページが文字化けする原因は、大体がmetaタグで文字コードを指定出来ていない事が多いです。
canvasタグを用意
canvasタグを用意します。このcanvasタグへJavaScriptでテキストを描画します。
<canvas id="canvas"></canvas>
canvasとは
HTML5のcanvas要素は、JavaScriptで図形などを描画することが出来る領域です。
JavaScript部分
JavaScript部分の解説です。
canvasへテキストを描画
canvasタグのエレメントを取得します。
var canvas = document.getElementById('canvas');
canvasタグへテキストを描画します。
var ctx = canvas.getContext('2d');
ctx.font = "30px serif";
ctx.fillStyle = "blue";
ctx.fillText('Canvas', 10, 30);
ctx.font = "30px 'MS ゴシック'";
ctx.strokeStyle = "green";
ctx.strokeText('Text', 10 + (30/2 * (6 + 1)), 30 + 30);
ctx.font = "30px serif";
ctx.fillStyle = "red";
ctx.fillText('Sample', 10 + (30/2 * (6 + 1)) + (30/2 * (4 + 1)), 30 + 30 + 30);
canvas関係のメソッド
- getContext('2d’)
- 線や円などを描画するメソッドを持っている組み込みオブジェクトを取得。
- font
- フォントのスタイル・サイズ・種類を指定。
- fillStyle
- 塗りつぶしの色やスタイルを指定。
- fillText(text, x, y, maxWidth)
- 塗りつぶしのテキストを指定座標に描画。
- strokeStyle
- 線や輪郭の色やスタイルを指定。
- strokeText(text, x, y, maxWidth)
- 輪郭のテキストを指定座標に描画。
おわり
今回はcanvasタグへテキストを描画するプログラミングコードを解説しました。
ディスカッション
コメント一覧
まだ、コメントがありません