开发者

Javascript Canvas drawing problem

So I have a bunch of javascript to make some random points, and then connects them via a minimum spanning tree. That all works fine.

Then after that it draws the points and paths onto the canvas; and it draws an im开发者_Python百科age like this:

Javascript Canvas drawing problem

- Randomly generated each time.

The problem I have with this, is that I'd like to have each of the circles be a black circle with a yellow outline. The circles are drawn like so:

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

and that works fine, but I want to draw a black circle, and have a yellow trace. I want to do it this way because it's much easier than stopping the lines that join the dots stop a few pixels earlier than they normally would.

This was my attempt:

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

but it draws this:

Javascript Canvas drawing problem

?!! It redraws over the other path. Why?!

Zip of the page: http://rapidshare.com/files/415710231/page.zip (html file and a css file inside the zip). The snippet of code for drawing the circles starts at line 164.


You need to call context.beginPath() before you draw each part to clear the path. stroke() and fill() leave the path in place, so you are redrawing the lines at each step.

You can also take advantage of the path sticking around, and reuse the path for the filled black circles and the outline. It avoids code duplication and should be slightly faster. The code would look like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜