Peter Kellner
Peter Kellner

Reputation: 15498

Can't figure out why HTML Canvas arc fails with a parameter

I've got a very simple HTML page with a Canvas element.

When I pass the 4th parameter of arc as Math.PI * 2, I get the red circle I expect, but when I try to do the same thing passing 3.1415 * 2, I get no red circle.

I expect that in both cases I would get the same result with a red circle.

const canvas = document.getElementById("solar-canvas");
const context = canvas.getContext("2d", { alpha: false });

context.beginPath();
context.fillStyle = "red";


//const val = Math.PI * 2;
const val = 3.1415 * 2;
context.arc(190,150, 9, 0, val, true);




context.fill();
context.closePath();
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Simple Solar System</title>
  </head>

  <body>xxx
    <canvas
      id="solar-canvas"
      width="380"
      height="300"
      style="border: 1px solid #aaaaaa"
    ></canvas>
  
  </body>
</html>

Upvotes: 0

Views: 38

Answers (1)

Helder Sepulveda
Helder Sepulveda

Reputation: 17614

I think what you are experiencing is best seen on an example:

const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
let end = 0

function draw() {      
  context.clearRect(0, 0, 90, 90)
  context.beginPath()
  context.arc(22, 40, 20, 0, end, true);
  context.stroke();
  
  context.beginPath()
  context.arc(65, 40, 20, 0, end);
  context.fillText(end, 10,10)
  context.stroke();
    
  end += 0.05
}

setInterval(draw, 100)
<canvas id="canvas" width="90" height="90"></canvas>

3.1415 * 2 is close to Math.PI * 2 but not exactly the same...
It's not failing just the arc is very small

PI 3.14159265... could be rounded to 3.1416
if you use that in your counterclockwise arc you will get the full circle.


There is some weirdness with that last parameter counterclockwise why with big numbers it keeps deleting the arc that might be an interesting question to look into

Upvotes: 1

Related Questions