Bump mapping heightmap

by realhunts

HTML

<canvas id="canvas"></canvas>

JavaScript

maxXY = 256;
originXY = 128;

//Returns a positive int, up to 256, 
function luminosity(d) {
    return Math.round(
        Math.min(
            Math.max(d, 0)
        , maxXY - 1)
    );
}

//Function tranxlates (x,y) coords into a linear array position
function findPixelData(x, y) {
    return (y * 256 + x) * 4
}

//Calls a provided function over a 256x256 element array.
function cycleThrough(d) {
    for (y = maxXY; y--;) {
        for (x = maxXY; x--;) {
            d(x, y);
        }
    }
}

function L(_ctx, mouseX, mouseY, deltaHypotenuse) {
    pixelData  = _ctx.getImageData(0, 0, maxXY, maxXY).data;
    canvasData = _ctx.getImageData(0, 0, maxXY, maxXY);
   
    cycleThrough(function (x, y) {

        //Find the pixelData value for each pixel
        var pixelData1 = pixelData[findPixelData(x, y + 1) + 2];
        var pixelData2 = pixelData[findPixelData(x, y - 1) + 2];
        var pixelData3 = pixelData[findPixelData(x + 1, y) + 2];
        var pixelData4 = pixelData[findPixelData(x - 1, y) + 2];

        /*
            Set the intensity of a point to the luminosity of
            a value from the array where we generated the hypotenuses (see code below).
            
            The value we're looking for is calculated based on mouse movement, and difference between pixels.
        */
        intensity = luminosity(
            deltaHypotenuse[
                  luminosity( pixelData1 - pixelData2 - y + mouseY) * maxXY 
                + luminosity( pixelData3 - pixelData4 - x + mouseX)
            ]
        );

        //This sets RGB of pixel data to the value of intensity.
        for (i = 3; i--;) { 
            canvasData.data[findPixelData(x, y) + i] = intensity; 
        }

        //This paints the whole background's channel, makes it black.
        canvasData.data[findPixelData(x, y) + 3] = maxXY - 1;
    });
    _ctx.putImageData(canvasData, maxXY, 0);
}


//Generate an array with values that show the distance between (x,y) point and every...