【问题标题】:Javascript Canvas drawing problemJavascript Canvas 绘图问题
【发布时间】:2010-08-29 06:00:23
【问题描述】:

所以我有一堆 javascript 来制作一些随机点,然后通过最小生成树连接它们。一切正常。

然后在画布上绘制点和路径;它会画出这样的图像:

- 每次随机生成。

我遇到的问题是,我想让每个圆圈都是带有黄色轮廓的黑色圆圈。圆圈是这样绘制的:

context.fillStyle = "#ffff00";
for(var i = 0; i < syscount; i++){
    context.moveTo(systemsX[i],systemsY[i]);
    context.arc(systemsX[i],systemsY[i],4,0,Math.PI*2,true);
}
context.fill();

效果很好,但我想画一个黑色的圆圈,并有一个黄色的痕迹。我想这样做是因为它比停止连接点的线条比通常更早停止几个像素要容易得多。

这是我的尝试:

context.fillStyle = "#000000";
for(var i = 0; i < syscount; i++){
    context.moveTo(systemsX[i],systemsY[i]);
    context.arc(systemsX[i],systemsY[i],ssize,0,Math.PI*2,true);
}
context.fill();

context.strokeStyle = "#ffff00";
for(var i = 0; i < syscount; i++){
    context.moveTo(systemsX[i]+ssize,systemsY[i]);
    context.arc(systemsX[i],systemsY[i],ssize,0,Math.PI*2,true);
}
context.stroke();

但它画了这个:

?!!它在另一条路径上重绘。为什么?!

页面的 Zip:http://rapidshare.com/files/415710231/page.zip(zip 中的 html 文件和 css 文件)。绘制圆圈的代码 sn-p 从第 164 行开始。

【问题讨论】:

  • 感谢您编辑图片!
  • 没问题。我认为您的声誉应该足够高,您现在可以发布图片和多个链接。

标签: javascript html canvas


【解决方案1】:

您需要在绘制每个部分之前调用context.beginPath() 以清除路径。 stroke()fill() 保留路径,因此您在每一步都重新绘制线条。

您还可以利用周围的路径,并将路径重复用于填充的黑色圆圈和轮廓。它避免了代码重复,并且应该稍微快一些。代码如下所示:

// Clear out the existing path and start a new one
context.beginPath();

// Add the circles to the newly-created path
for(var i = 0; i < syscount; i++){
    context.moveTo(systemsX[i]+ssize,systemsY[i]);
    context.arc(systemsX[i],systemsY[i],ssize,0,Math.PI*2,true);
}

// Fill them in with black
context.fillStyle = "#000000";
context.fill();

// Draw the outline with yellow
context.strokeStyle = "#ffff00";
context.stroke();

【讨论】:

  • 是的,我意识到我需要 .beginPath() 就在我来检查之前。没注意到我可以避免再次循环,谢谢!!
猜你喜欢
  • 1970-01-01
  • 2011-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-27
  • 2019-03-30
  • 2018-02-27
  • 2011-05-11
相关资源
最近更新 更多