HTML5画布 - 绘制线段和圆圈 - 一个圆圈的不同颜色

时间:2016-06-24 00:29:25

标签: javascript html5 canvas

我尝试绘制由段连接的圆圈。我希望这些线段有黑色和圆圈蓝色,除了第一个圆圈(位于画布的中心,必须是黑色)。

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

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

如果有人能够发现绕过这个问题的错误。

提前致谢

1 个答案:

答案 0 :(得分:0)

您需要开始一条新路径来填充您的蓝色圆圈

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

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

fiddle here

相关问题