I have an 2d array of heights in javascript for a portion of a map. I would like to paint them as a relief map : http://www.howardmodels.com/0-topographic/landform-maps-models/gusev-crater/gusev-crater1.jpg
with shaded mountain side开发者_如何转开发s and such.
Any good ideas on how to do this? Part of the goal is to keep the computational intensity low (this would be part of a web based game).
If you can wade through the code check this out, something I did a while back.
http://somethinghitme.com/projects/canvasterrain/
Only drawback (besides code clarity) is its pretty intensive (especially the shadow map function).
The demo below is just the shadow map function working by itself.
Live Demo
Animated Version
Could be cleaned up for sure. What this does is create some test data, basically making a height map that has a raised square in the center. You can see how the shadow goes out from there. This is all based upon the light sources height, and position in comparison to the heightmap. note I do not draw the height data, thats why the image is white. Its just to give you an idea of what this does. Would be easy to apply any 2d array of data to it.
//Create Shadowmap
function drawShadowMap(size, sunPosX, sunPosY, sunHeight){
var ctx = mapCanvas.getContext("2d"),
x = 0, y = 0,
idx,
colorFill = 0,
sunX, sunY, sunZ,
pX, pY, pZ,
mag, dX, dY, dZ;
// Suns position
sunX = sunPosX;
sunY = sunPosY;
sunZ = sunHeight;
for(x = 0; x <= mapDimension; x += unitSize){
for(y = 0; y <= mapDimension; y += unitSize){
dX = sunX - x;
dY = sunY - y;
dZ = sunZ - map[x][y];
mag = Math.sqrt(dX * dX + dY * dY + dZ * dZ);
dX = (dX / mag);
dY = (dY / mag);
dZ = (dZ / mag);
pX = x;
pY = y;
pZ = map[x][y];
while(pX >= 0 && pX < mapDimension && pY >= 0 && pY < mapDimension && pZ <= sunZ){
if((map[round(pX)][round(pY)]) > pZ){
ctx.fillStyle = "rgba(" + 0 + "," + 0 + "," + 0 +"," + 0.7 + ")";
ctx.fillRect (x, y, unitSize, unitSize);
break;
}
pX += (dX * unitSize);
pY += (dY * unitSize);
pZ += (dZ * unitSize);
}
}
}
}
map[x][y]
is the data for the map, and is a value between 0-1.
Trying to find some of the resources I used I came across this gamedev article, there was another I used in addition to that but I can't seem to find it now unfortunately.
精彩评论