square & circle

browsercanvasexamples ⟩ square & circle

💾 replit: square & circle

// ⭐ 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
});

Last updated