liguofeng29’s blog

個人勉強用ブログだっす。

HTML5のcanvas要素 - テキストを描く

テキストを描く二つのメソッド

  1. fillText(String text, float x, float y, [float maxWidth])
  2. strokeText(String text, float x, float y, [float maxWidth])
<!DOCTYPE html>
<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=SJIS" />
   <title> テキストを描く </title>
</head>
<body>
<h2> テキストを描くサンプル </h2>
<canvas id="canvas" width="400" height="300"
    style="border:1px solid black"></canvas>
<script type="text/javascript">
   // canvas要素取得
   var canvas = document.getElementById("canvas");
   // CanvasRenderingContext2D取得
   var ctx = canvas.getContext("2d");
   
   ctx.fillStyle = "#00f"; // 色
   ctx.font = "48px serif"; // フォント
   ctx.textBaseline = "top"; // 位置
   ctx.fillText("テキストを書きました。", 0, 0); // テキスト内容
   
   ctx.strokeStyle = "#f0f"; // 色
   ctx.font="bold 45px serif"; // フォント
   // 内部空のテキスト
   ctx.strokeText("テキストを書きました。", 0, 50);
</script>
</body>
</html>

f:id:liguofeng29:20160123181357p:plain