简体   繁体   中英

HTML5 canvas: Mutliple arc shapes with for loop

Hi there my problem with the code below is the the arc is creating 1 shape not the ten specified in the for loop...

If I was to change from arc to $cd.fillRect(10,20,$x,$y); then that would create 10 different rectangles but not the arc... what am I misunderstanding here?

 
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;

}

笔触和填充应该在循环中

I think you forgot to multiply x with i .

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM