HTML5画布:带有for循环的多个弧形

时间:2011-02-11 07:41:37

标签: javascript html5 canvas for-loop geometric-arc

您好我的问题是下面的代码是弧创建1个形状而不是for循环中指定的10个...

如果我要从弧线变为$cd.fillRect(10,20,$x,$y);,那么会产生10个不同的矩形而不是弧线......我在这里误解了什么?

 
var $canvas = $('#canvas-one')[0],
    $cd;

if ($canvas.getContext) {

$cd = $canvas.getContext('2d');

for (i = 0; i <= 10; i++) {

    $cd.fillStyle = "rgb(" + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + ")";

    $cd.strokeStyle = "rgb(" + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + ")";

    var $x = 300 + Math.floor(Math.random() * 101);
    var $y = 300 + Math.floor(Math.random() * 101);
    var $radius = 0.1 + Math.floor(Math.random() * 6);

    $cd.beginPath();

    $cd.arc($x, $y, $radius, 0, Math.PI * 2, true);

}

$cd.stroke();
$cd.fill();

//$canvas.width = $canvas.height;

}

2 个答案:

答案 0 :(得分:1)

笔划和填充应该在循环中

答案 1 :(得分:0)

我认为您忘记将xi相乘。

for (let i = 0; i < 10; i++) {
    context.fillStyle = "rgb(" + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + ")";
    context.beginPath();
    context.arc(i * x, y,15, 0, 2 * Math.PI,true);
    context.fill();