Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript context.arc() not drawing a Circle, but an Oval instead

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>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading