Wednesday, January 9, 2019

Web image blocks!

A specimen of the font Lobster.
Blocks of light adventure.


Find the code described in this post at GitHub!

Logical Problems

You've probably seen images laid out in such a way that they appear to be tiles or blocks in a wall where all the images are justified so there are no ragged edges. I remember that when I first did I spent a few moments casually pondering how it was down. Much, much, later I decided to create a simple website for my brother Alex (aka the pencilist) and display his art in block layout.

As the maintainer of the web site I had some requirements: I needed to be able to add new images so that they appeared as the upper left-most image, this meant that the number of rows and images that make up the rows would change; I didn't want to have to do any math when an image was added; I didn't want to copy and paste a lot of formatted HTML; I didn't want to update attribute values (like width and height) for older images when a new one was added and the older image's row might change; also what if I needed to move images around later or only display filtered images! After thinking about it for a little while I had an "A ha!" moment and came up with a solution. Now this is probably not a unique solution but it's interesting because there are two logical problems that need to be solved to create a layout like this.

Images in a row

Notice that in scrollable solutions the images are laid out in rows and each image in a row has the same height; however every row may have a different height. From this I inferred that a decision was made to include certain images in each row so the first thing I did was answer this question:

"How may images can be in a row?"

It occurred to me that a row could be defined as a vector of "blocks" each with an equal width. Based on an image's aspect ratio (width divided by height) I could assign each image a width in "blocks."

arThreeTwo: 3 / 2, // 1.5
arTwoOne: (2 / 1) + .2, // 2 (plus a small amount of buffer)

/**
 * Calculates how many blocks each image will occupy in a row.
 * @param {number} aspectRatio The width of the image divided by the height of the image.
 * @returns {number} The number of blocks.
 */
calculateBlocks: function (aspectRatio) {
    var blocks = 1; // portrait image
    if (this.arTwoOne < aspectRatio) {
        blocks = 6; // panoramic image
    } else if (this.arThreeTwo < aspectRatio) {
        blocks = 3;
    } else if (1 < aspectRatio) {
        blocks = 2.5;
    }

    return blocks;
}

I determined that I would display the images in a container so that each row was 800 pixels wide. Based on the appearance of a portrait image I decided that a row of six blocks would look good. Now iterating over the collection of all images from the beginning I create an array whose elements will represent the images in a row. I add the blocks the next image requires to the total number of blocks currently in the array, if the result is less than or equal to six I push the image onto the array otherwise a new array is created for the next row and the image is pushed onto the new array (taking care to handle the end of the collection where there may be a row that takes up less than six blocks).

I had an answer to the first question.

Proportions

The second question was much more simple to answer:

"How are the images in a row sized to fit exactly 800 pixels and all have the same height?"

The hardest part of answering this question (both questions really) is that the dimensions of some number of images has to be known; in this case at least the next six images that could potentially make up an entire row. For my implementation the information about the images is contained in an array of objects, including the dimensions of the images in the objects was trivial. However other possibilities exist including downloading a set of six images and measuring them in hidden <img> elements to determine their dimensions. This is more complex but it has greater flexibility since the size of the images doesn't need to be known ahead of time.

In any case once the image dimensions are in hand and all the images to be placed in a row are known the dimensions of the second and subsequent images in a row are scaled so that their heights match the height of the first image.

// First scale all of the image dimensions to the height of the first image.
var firstImage = images[0];
var sizes = [{ height: firstImage.height, width: firstImage.width }];

var b;
for (var i = 1; i < images.length; i++) {
    b = images[i];
    sizes.push({ height: firstImage.height, width: (firstImage.width * b.height) / b.width });
}

Add up the widths of the images to get the width of the entire row.

// Find the total width of all the scaled dimensions.
var totalScaledWidth = sizes.reduce(function (acc, x) {
    return acc + x.width;
}, 0);

Now scale the total row dimensions so the row width is 800. Doing so provides the display height that will be applied to all of the <img> elements in the row.

// Find the height that will allow all the images to fit the maximum
// width.
var newHeight = (firstImage.height * 800) / totalScaledWidth;

Finally calculate the display width of each <img> in the row.

for (var i = 0; i < images.length; i++) {
    // Update each image's dimensions to fit in the brick wall layout.
    image = images[i];
    image.displayWidth = Math.round((image.width * newHeight) / image.height);
    image.displayHeight = Math.round(newHeight);
}

Once I had the information for the images I could then set the height and width attributes of the <img> elements to size them appropriately (createElement is a helper function that returns an HTML element).

var img = createElement("img", { alt: image.title }, null, { height: image.displayHeight + "px", width: image.displayWidth + "px" });

There are a variety of concerns that are left as exercises for the reader such as: downloading the images in the desired order (newest to oldest) and so that they display reasonably quickly, indications to your user where images will appear, displaying the images in rows with proper alignment requiring a dose of CSS, and cropping images to maintain a specific row height (very long images) or minimum image width (very tall images).

Have a better solution? Let's hear about it in the comments!

No comments:

Post a Comment