Reputation: 192
I cannot draw a proper circle, no matter what. I'm always getting an ellipse. Here's example code to show you what I mean:
function canvasClicked(number) {
var c = "canvas" + number;
var canvas = document.getElementById(c);
var context = canvas.getContext("2d");
var centerX = 150;
var centerY = 75;
context.beginPath();
context.arc(centerX, centerY, 70, 0, Math.PI * 2);
context.lineWidth = 10;
context.strokeStyle = "red";
context.stroke();
}
#canvas1 {
width: 200px;
height: 200px;
border: 1px solid black;
}
<canvas id="canvas1" onclick="canvasClicked(1)"></canvas>
I tried to identify the cause of the issue but without any success. I know that the centerX and centerY should be equal to element.width / 2 and element.height / 2 but that gives me even more awkward results, moving the ellipse away from the center of the box.
Upvotes: 1
Views: 192
Reputation: 54649
The problem is this:
#canvas1 {
width: 200px;
height: 200px;
border: 1px solid black;
}
while using this:
<canvas id="canvas1" onclick="canvasClicked(1)"></canvas>
or to be more exact: The visible css dimensions are not the same as the underlying canvas dimensions. Because not setting them as attributes on the element:
<canvas id="canvas1" onclick="canvasClicked(1)" width="200" height="200"></canvas>
will result in the canvas using the default values 300x150px.
demo: http://jsbin.com/geralevi/1/
further reference: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Basic_usage
Note: If your renderings seem distorted, try specifying your width and height attributes explicitly in the attributes, and not using CSS.
Upvotes: 5