简体   繁体   中英

HTML5 Canvas - Draw segments and circles - Different color for one circle

I try to draw circles joined by segments. I want the segments to have black color and the circles blue color except for the first circle (which is at the center of canvas and must be black).

Here's a capture showing the current result :

在此输入图像描述

As you can see, the result is good except for the first circle which remains blue.

Here's the code :

// Get context
context = canvas.getContext('2d');

context.fillStyle = 'white';
context.fillRect(0, 0, 650, 650);

// Draw black segments
context.beginPath();
context.moveTo(x0, y0);
context.lineTo(x1, y1);
context.lineTo(x2, y2);
context.lineTo(x3, y3);
context.strokeStyle = 'black';
context.stroke();

// Draw circles (blue except for the first which is black)
context.beginPath();
// Create sub-path
context.moveTo(x0, y0);
context.arc(x0, y0, radius, 0, 2 * Math.PI);
context.fillStyle = 'black';
context.fill();
context.closePath();
// Close sub-path

// Create sub-path
context.moveTo(x1, y1);
context.arc(x1, y1, radius, 0, 2 * Math.PI);
context.closePath();
// Close sub-path

// Create sub-path
context.moveTo(x2, y2);
context.arc(x2, y2, radius, 0, 2 * Math.PI);
context.closePath();
// Close sub-path

// Create sub-path
context.moveTo(x3, y3);
context.arc(x3, y3, radius, 0, 2 * Math.PI);
context.closePath();
// Close sub-path

// Fill all sub-paths
context.stroke();
context.fillStyle = 'blue';
context.fill();

It seems that I can't fill only one circle by putting :

    context.beginPath();
    // Create sub-path
    context.moveTo(x0, y0);
    context.arc(x0, y0, radius, 0, 2 * Math.PI);
    context.fillStyle = 'black';
    context.fill();
    context.closePath();
    // Close sub-path

If someone could see what's wrong to circumvent this issue.

Thanks in advance

You need to begin a new path to fill in your blue circles

context.beginPath();
//draw black circle
context.fill();

context.beginPath();
//draw blue arcs
context.fillStyle='blue
context.fill();

fiddle here

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