Why is the canvas circle not looking like a circle

2019-06-05 05:41发布

问题:

I have a very simple code that should draw a circle, but its not looking like one, and not at the right position The coordinates are all somewhat shifted. The canvas is set to style="width: 600px; height: 600px;". I tried it on chrome and safari - looks the same so it's not a browser bug. So my questions are (there is probably one answer for both):

  1. If I am putting the center at (100, 100), why is the circle not at an equal distance from the left border, that it is from the top border?
  2. Why is the (300, 300) point out of the canvas, and not in the center?

The code:

var context = document.getElementById('c').getContext("2d");
context.fillStyle = 'black';
context.fill();
context.beginPath();
context.arc(100, 100, 30, 0, 2 * Math.PI, true);
context.stroke();

How it looks:

Edit

According to the comment I found out that writing <canvas id="myCanvas" style="width: 578px; height: 200px;"></canvas> is causing this problem, and writing <canvas id="myCanvas" width="578" height="200"></canvas> solves it. Anyone knows why?

回答1:

This is documented in the HTML5 Canvas spec.

The HTML attributes width="x" height="y" describe the drawing area of the canvas and default to 300 × 150 px. As a side-effect, they describe the default visible size of the canvas.

The CSS properties width: x; height: y; set on the canvas can stretch/compact that drawing area, but they don't change its size.

In your case, the browser stretches the default drawing area (300 × 150 px) to meet the given CSS of 600 × 600 px.



回答2:

This example shows how to draw a circle on canvas: http://www.html5canvastutorials.com/tutorials/html5-canvas-circles/

Also, you need to set the width and height attributes on the canvas element rather as a style attribute like so:

<canvas id="c" width="600" height="600" style="background-color:yellow;"></canvas>