views:

50

answers:

1

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 image like this:

First example

- 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:

Second example

?!! 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.

+1  A: 

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();
Matthew Crumley
Yeah, i realised i needed the .beginPath() in there just before i came to check this.Didn't notice i could avoid doing the loop again though, thanks!!
will