在画布中间画一个圆圈

时间:2014-04-09 10:04:25

标签: javascript css canvas

有 -

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/

但我得不到准确的圈子。我怎样才能让它成为准确的圆圈?

4 个答案:

答案 0 :(得分:4)

您需要明确设置画布的大小,否则它将获得默认大小:300x150。

你应该做这样的事情

<canvas id="myCanvas" width="500" height="400"></canvas>

或通过javascript(在获取上下文之前)

canvas.width = 500;
canvas.height = 400;
var context = canvas.getContext('2d');

答案 1 :(得分:4)

Demo Fiddle

如果您只想在CSS中设置画布大小,请将代码更改为:

<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>

答案 2 :(得分:1)

您需要设置画布的宽度,如下所示:

<canvas id="myCanvas" width="500" height="400"></canvas>

答案 3 :(得分:0)

在开始路径后放置代码:

    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;

}