How to draw a circle in HTML5 Canvas using JavaScript?

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

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

相关标签:
3条回答
  • 2020-12-17 08:32

    Creating shapes is easier using new Canvas Path2D, which uses the same canvas drawing API, and allow separation of the declaration from drawing itself, and reuse of complex geometry:

    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');
    var centerX = canvas.width / 2;
    var centerY = canvas.height / 2;
    var radius = 70;
    
    let circle = new Path2D();  // <<< Declaration
    circle.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
    
    context.fillStyle = 'blue';
    context.fill(circle); //   <<< pass circle to context
    
    context.lineWidth = 10;
    context.strokeStyle = '#000066';
    context.stroke(circle);  // <<< pass circle here too
    body {
    margin: 0px;
    padding: 0px;
    }
    <canvas id="myCanvas" width="578" height="200"></canvas>

    0 讨论(0)
  • 2020-12-17 08:35

    Here is how to draw a circle using JavaScript in HTML5:

    const canvas = document.getElementById('myCanvas');
    const context = canvas.getContext('2d');
    const centerX = canvas.width / 2;
    const centerY = canvas.height / 2;
    const radius = 70;
    
    context.beginPath();
    context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
    context.fillStyle = 'green';
    context.fill();
    context.lineWidth = 5;
    context.strokeStyle = '#003300';
    context.stroke();
    body {
      margin: 0px;
      padding: 0px;
    }
    <canvas id="myCanvas" width="578" height="200"></canvas>

    0 讨论(0)
  • 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();
    
    0 讨论(0)
提交回复
热议问题