How to draw a circle in HTML5 Canvas using JavaScript?

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

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

3条回答
  •  萌比男神i
    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;
    }

提交回复
热议问题