Reputation: 11032
Having -
HTML -
<canvas id="myCanvas" >
</canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 30;
context.beginPath();
context.arc(centerX,centerY, radius, 0, 2 * Math.PI);
context.fillStyle = 'blue';
context.fill();
</script>
CSS-
#myCanvas {
border:2px solid;
display:inline-block;
width:500px;
height:400px;
}
http://jsfiddle.net/urielz/3E656/
but I get not accurate circle . How can I make it accurate circle ?
Upvotes: 1
Views: 3835
Reputation: 5336
You need to set explicitly the size of your canvas, otherwise it will get the default size: 300x150.
you should do something like this
<canvas id="myCanvas" width="500" height="400"></canvas>
or via javascript (before getting the context)
canvas.width = 500;
canvas.height = 400;
var context = canvas.getContext('2d');
Upvotes: 5
Reputation: 71230
If you just want set the canvas size in CSS, change your code to:
<canvas id="myCanvas"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var style = window.getComputedStyle(canvas);
if (canvas.getContext) {
canvas.width = parseInt(style.getPropertyValue('width'));
canvas.height = parseInt(style.getPropertyValue('height'));
}
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 30;
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'blue';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke();
this.arc(x, y, radius, 0, Math.PI * 2, false);
this.fill();
</script>
Upvotes: 6
Reputation: 17795
You need to set the width of your canvas, like so:
<canvas id="myCanvas" width="500" height="400"></canvas>
Upvotes: 1
Reputation: 2365
Place below code after begin path:
var centerX = canvas.width;
var centerY = canvas.height;
context.arc(centerX*0.5,centerY*0.5,10,0 ,radius, 0, 2 * Math.PI);
Css:
#myCanvas {
border:2px solid;
display:inline-block;
width:600px;
height:300px;
}
Upvotes: 0