# square & circle

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

{% tabs %}
{% tab title="💾 程式" %}
![](https://2527454625-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MfvEFZnSBhKT6fJmus0%2Fuploads%2FHpe598jC8AzVrsPwwLTQ%2Fsquare_circle.png?alt=media\&token=87be9dc8-04f3-4e55-9689-67cbdfd9b39c)

: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 %}
