How to draw a circle in HTML5 Canvas using JavaScript?

后端 未结 3 1050
离开以前
离开以前 2020-12-17 08:05

How to draw a simple circle in HTML5 Canvas using minimum JavaScript code?

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-17 08:45

    First of all, you need to get the canvas context:-

    const canvas = document.querySelector('#canvas');
    const ctx = canvas.getContext('2d');
    

    Now let us define the position and radius:-

    const X = canvas.width / 2;
    const Y = canvas.height / 2;
    const radius = 45;
    

    Now let us set the color and line width:-

    ctx.lineWidth = 3;
    ctx.strokeStyle = '#FF0000';
    

    Now, to draw the circle, we have to use the arc method and set the angle to 2 X π

    ctx.beginPath();
    ctx.arc(X, Y, radius, 0, 2 * Math.PI, false);
    ctx.stroke();
    

提交回复
热议问题