Reputation: 5072
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):
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:
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?
Upvotes: 1
Views: 370
Reputation:
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
.
Upvotes: 3
Reputation: 8588
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>
Upvotes: 2