HTML Canvas 文字
HTML Canvas 文字
要在畫布上繪製文字,最重要的屬性和方法是
-
font
- 定義文字的字型屬性 -
fillText()
- 繪製“填充”文字 -
strokeText()
- 繪製“描邊”文字(無填充)
font 屬性
font
屬性定義要使用的字型和字型大小。
此屬性的預設值為“10px sans serif”。
fillText() 方法
fillText()
方法用於繪製“填充”文字。
fillText()
方法具有以下引數
引數 | 描述 |
---|---|
text | 必需。要繪製的文字字串 |
x | 必需。字串起始點的 x 座標 |
y | 必需。字串起始點的 y 座標 |
maxWidth | 可選。文字字串的最大寬度 |
示例
將字型設定為 50px“Arial”,並在畫布上寫入填充文字。從 (10,80) 位置開始
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.font = "50px Arial";
ctx.fillText("Hello World",10,80);
</script>
自己動手試一試 »
strokeText() 方法
strokeText()
方法用於繪製“描邊”文字。
strokeText()
方法具有以下引數
引數 | 描述 |
---|---|
text | 必需。要繪製的文字字串 |
x | 必需。字串起始點的 x 座標 |
y | 必需。字串起始點的 y 座標 |
maxWidth | 可選。文字字串的最大寬度 |
示例
將字型設定為 50px“Arial”,並在畫布上寫入描邊文字。從 (10,80) 位置開始
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.font = "50px Arial";
ctx.strokeText("Hello World",10,80);
</script>
自己動手試一試 »
示例
為字型新增粗體和斜體
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.font = "bold italic 50px Arial";
ctx.strokeText("Hello World",10,80);
</script>
自己動手試一試 »