2016-06-24 246 views
1

我尝试绘制由段加入的圆。除了第一个圆(它位于画布的中心并且必须是黑色)之外,我希望这些分段具有黑色和圆形蓝色。HTML5画布 - 绘制线段和圆圈 - 一个圆圈的不同颜色

这里是显示当前结果的捕获:

enter image description here

正如你所看到的,其结果是,除了这仍然是蓝色的第一圈不错。

下面的代码:

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

看来我无法通过将只填写一个圆圈:

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 

如果有人能看到什么是错的,以规避这个问题。

在此先感谢

回答

0

你需要开始一个新的路径来填补你的蓝圈

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

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

fiddle here

+0

谢谢,但我得到的另外一个问题,如果我把灰色而不是黑色,你可以看到它在第一个圆的中心和它的边缘之间画了一段小片段:https://jsfiddle.net/3ouLju43/ – youpilat13

+0

我也在学习这个:)你需要在移动之后开始路径:见第23行-24这里:https://jsfiddle.net/3ouLju43/1/ – derp

+0

完美!问候 – youpilat13