0

Hello I have a simple question. I am trying to draw a circle with ctx.arc(), but the output is always an oval. May I know what is my mistake here?

const canvas = document.querySelector("#canvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.fillStyle = "red";
ctx.arc(300, 130, 100, 0, Math.PI * 2);
ctx.fill();
#canvas {
  border: 1px solid black;
  width: 640px;
  height: 640px;
}
<canvas id="canvas">My Canvas</canvas>
Anurag Srivastava
  • 14,077
  • 4
  • 33
  • 43
zach
  • 37
  • 6

1 Answers1

1

The canvas needs to know the number of logical pixels in both height and width to draw the shapes in the right dimensions.

Explicitly set the width and height property of the canvas to fix the drawing.

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

canvas.width = 640;
canvas.height = 640;

ctx.beginPath();
ctx.fillStyle = "red";
ctx.arc(300, 130, 100, 0, Math.PI * 2);
ctx.fill();
#canvas {
  border: 1px solid black;
  width: 640px;
  height: 640px;
}
<canvas id="canvas">My Canvas</canvas>

Alternatively you could also set the properties as attributes in your HTML.

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

ctx.beginPath();
ctx.fillStyle = "red";
ctx.arc(300, 130, 100, 0, Math.PI * 2);
ctx.fill();
#canvas {
  border: 1px solid black;
  width: 640px;
  height: 640px;
}
<canvas id="canvas" width="640" height="640">My Canvas</canvas>
Emiel Zuurbier
  • 19,095
  • 3
  • 17
  • 32