Last active
August 22, 2021 07:59
-
-
Save YonatanKra/bd49d529bebf356ea9ca14b9738da1ed to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function landscapeColors(percentage) { | |
const colorVariety = 3; | |
const colorStep = 360 / colorVariety; | |
const colorIndex = Math.floor(percentage * colorVariety); | |
const hue = | |
colorStep * colorIndex + colorStep * (percentage - (colorIndex * 100) / 3); | |
const lightness = percentage < 0.01 ? 100 : 50; | |
const saturation = 100; | |
const terrainType = | |
lightness === 100 | |
? "snow" | |
: colorIndex === 0 | |
? "mountains" | |
: colorIndex === 1 | |
? "plains" | |
: "water"; | |
return { | |
hsl: `hsl(${hue < 360 ? hue : hue - 360}, ${saturation}%, ${lightness}%)`, | |
terrainType | |
}; | |
} | |
function draw(terrain_matrix) { | |
const ctx = canvas.getContext("2d"); | |
const paths = { | |
water: new Path2D(), | |
plains: new Path2D(), | |
mountains: new Path2D(), | |
snow: new Path2D() | |
}; | |
ctx.clearRect(0, 0, CANVAS_HEIGHT, CANVAS_WIDTH); | |
ctx.beginPath(); | |
terrain_matrix.forEach((pixelsRow, rowIndex) => { | |
const y = rowIndex * MATRIX_DIMENSIONS.pixelHeight; | |
pixelsRow.forEach((pixel, pixelIndex) => { | |
const x = pixelIndex * MATRIX_DIMENSIONS.pixelWidth; | |
const { hsl, terrainType } = getColor(pixel); | |
ctx.fillStyle = hsl; | |
ctx.fillRect( | |
x, | |
y, | |
MATRIX_DIMENSIONS.pixelWidth, | |
MATRIX_DIMENSIONS.pixelHeight | |
); | |
const tmpPath = new Path2D(); | |
tmpPath.rect( | |
x, | |
y, | |
MATRIX_DIMENSIONS.pixelWidth, | |
MATRIX_DIMENSIONS.pixelHeight | |
); | |
paths[terrainType].addPath(tmpPath); | |
}); | |
}); | |
ctx.closePath(); | |
return paths; | |
} | |
canvas.addEventListener("click", (event) => { | |
const pathsNames = Object.keys(paths); | |
const ctx = canvas.getContext("2d"); | |
const { top, left } = canvas.getBoundingClientRect(); | |
for (let i = 0; i < pathsNames.length; i++) { | |
if ( | |
ctx.isPointInPath( | |
paths[pathsNames[i]], | |
event.clientX - left, | |
event.clientY - top | |
) | |
) { | |
alert(`I've just hit the ${pathsNames[i]}`); | |
return; | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment