# 用時間當參數：秒數與 sin 呼吸

正式網址：https://newmediaart.course.monolab.world/snippets/time-breath

millis() ÷ 1000 就是開始到現在幾秒，丟進 sin() 再用 map() 換算成大小和亮度，圓就會像呼吸一樣一脹一縮。

- **分類**：時間與隨機
- **行數**：24 行（p5.js 1.x／2.x）

在自己 draw() 的開頭加 const t = millis() / 1000;，想要會動的數值就寫成 sin(t * TWO_PI / 週期秒數)，再用 map() 換算到要的範圍。

```js
// 用時間當參數：millis() 是開始到現在的毫秒，除以 1000 就是秒
function setup() {
  createCanvas(600, 600);
}

function draw() {
  background(20);
  const t = millis() / 1000; // 秒：電腦快慢都一樣
  // const t = frameCount / 60; // 另一種：用第幾格換算，電腦卡的時候會跟著變慢

  // 4 秒呼吸一次：sin 在 -1 到 1 之間來回
  // （有寫 angleMode(DEGREES) 的話，TWO_PI 改成 360）
  const breath = sin((t * TWO_PI) / 4);
  const d = map(breath, -1, 1, 120, 360); // 直徑
  const bright = map(breath, -1, 1, 90, 255);

  noStroke();
  fill(bright, 180, 120);
  circle(width / 2, height / 2, d);

  fill(255);
  textSize(16);
  text('t = ' + t.toFixed(1) + ' 秒', 16, 30);
}
```

## 同類常用指令・時間與隨機

- [在畫面上印出日期時間](https://newmediaart.course.monolab.world/snippets/datetime-text)
- [存檔名帶種子：喜歡的那張找得回來](https://newmediaart.course.monolab.world/snippets/seed-in-filename)

[回到全部常用指令](https://newmediaart.course.monolab.world/snippets)

[到 Hahow 報名](https://hahow.in/cr/creative-code)。價格與優惠以 Hahow 頁面為準。
