> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/browser/canvas/examples/square-and-circle.md).

# square & circle

[browser](/web/browser.md) ⟩ [canvas](/web/browser/canvas.md) ⟩ [examples](/web/browser/canvas/examples.md) ⟩ square & circle

{% tabs %}
{% tab title="💾 程式" %}
![](/files/eGxsbRBk0tzy3oOGcmkt)

:floppy\_disk: replit: [square & circle](https://replit.com/@pegasusroe/canvas-API#script.js)

```javascript
// ⭐ draw on <canvas> 2D context
function drawOnCanvas2D(selector, draw) {
    let canvas = document.querySelector(selector);
    if (!canvas) { console.log(`⛔ no such element: "${selector}"`); return; }
    let context = canvas.getContext("2d");
    if (draw) draw(context);
}

// 1st <canvas>
drawOnCanvas2D('#square', (ctx) => {
    ctx.fillStyle = '#f00';        // fill color = red
    ctx.fillRect(0, 0, 10, 10);    // fill a square
});

// 2nd <canvas>
drawOnCanvas2D('#circle', (ctx) => {
    ctx.beginPath();                         // new path
    ctx.arc(5, 5, 5, 0, 2 * Math.PI, true);  // circle to the path 
    ctx.fillStyle = "#00f";                  // fill color = blue
    ctx.fill();                              // fill path
});
```

{% endtab %}

{% tab title="📗 參考" %}

* [ ] JavaScript: The Definitive Guide (15.8 Graphics in a \<canvas>)
  {% endtab %}
  {% endtabs %}
