---
tags: Canvas, 隨手筆記
---
# 隨手筆記 - JS Canvas 語法筆記
## 本文目的
Canvas筆記
## 說明
vscode可以用下面的註解取得canvas的語法提示
```js
/** @type {HTMLCanvasElement} */
```
```javascript
// 取得canvas元素
let canvas = document.getElementById("myCanvas")
let ctx = canvas.getContext("2d")```
// 設定canvas大小
canvas.height = height
canvas.width = width
// 繪製填滿矩形
ctx.fillRect(x, y, width, height)
// 繪製只有線的矩形
ctx.strokeRect(x, y, width, height)
// 清除矩形範圍
ctx.clearRect(x, y, width, height)
// 繪製線
ctx.beginPath() // 宣告繪製路徑
ctx.moveTo(x, y) // 將畫筆移動至指定座標
ctx.lineTo(x, y) // 繪製直線
ctx.closePath() // 自動封閉路徑
// 細項設定
ctx.lineWidth = 5 // 指定路徑寬度
ctx.strokeStyle = 'red' // 指定路徑顏色
ctx.fillStyle = 'blue' // 指定路徑填色
ctx.stroke() // 路徑上色
ctx.fill() // 路徑填色
// 畫圓
ctx.beginPath(); // 要記得宣告開始繪製
ctx.arc(x, y, r, startAngle, endAngle)
ctx.fillStyle = fillStyle
ctx.fill()
ctx.stroke()
ctx.closePath()
ctx.fillText('Hellow World!', x, y) // 繪製填色文字
ctx.strokeText(text, x, y) // 繪製路徑文字
ctx.font = 'bold 18px "Microsoft JhengHei"'; // 設定文字大小、字體與粗體
// 設定文字水平對齊方式(start、end、left、right、center,預設為 start)
ctx.textAlign = 'center'
// 設定文字垂直對齊方式(top、hanging、middle、alphabetic、ideographic、bottom,預設為 alphabetic)
ctx.textBaseline = 'middle'
```