In javascript I have a map that I'd like to overlay with hexes and turn those hexes either green (land) or blue (water) based on how much land is in the hex. I assume that it has something to do with detecting the pixel color and if it is in a range that I consider blue then it gets counted as "water" once it reaches a certain number of pixels that are water, it just turns into a water tile.
The Problem I am having is that I know I have to define where to scan for all the pixels I want to color detect but I don't know how to do that with a hex. With a square grid i could do a nest for loop, but no clue how to do it with a hex.
To draw the hex I am using the following
function hex(x = 0, y = 0, side = 0, size = 10) {
ctx.beginPath();
ctx.moveTo(x + size * Math.cos(0), y + size * Math.sin(0));
for (side; side < 7; side++) {
ctx.lineTo(x + size * Math.cos(side * 2 * Math.PI / 6), y + size * Math.sin(side * 2 * Math.PI / 6));
}
}
But I don't see how I could use this for determining which pixels to detect. I'm not good at the maths.
You can scan hex line by line like rectangle. But your inner loop should vary its limits.
Your hex is flat-top, for (0,0)-centered hex left top vertex has coordinates (-side/2, -side * Sqrt(3)/2)
. Let p = Sqrt(3)/2
.
So outer (y-coordinate) loop limits are
-side * p .. side * p
For given y-coordinate x-limits are
-(side - 0.5 * Abs(y)) / p .. (side - 0.5 * Abs(y)) / p
Delphi code:
var
ix, iy, side: Integer;
cf: Double;
begin
cf := Sqrt(3) / 2;
side := 100;
for iy := - Round(cf * side) to Round(cf * side) do
for ix := - Round((side - 0.5 * Abs(iy) / cf)) to
Round((side - 0.5 * Abs(iy) / cf)) do
Canvas.Pixels[ix + 200, iy + 200] := clBlue;
generates
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.