Mubashir Qayyum Mubashir Qayyum - 6 months ago 12
Javascript Question

Gridify Images like Pinterest Layout on Canvas

I am using pixi.js to create an interactive app. I need to place images in different containers on the screen in the form of pinterest like layout or gridify them so that they look organize and nice. As Im working on canvas so plugins like gridify.js do not suport canvas and Im unable to find any plugin or code to get this working on canvas. Also, the images need to be clickable so I cannot use plugins like html to canvas conversion as they only generate the image.

Answer

I have found a solution for this by examining the gridify.js logic. Here is my code:

    var items = options.items;

    var width = options.containerWidth,
    item_margin = parseInt(options.margin || 0),
    item_width = parseInt(options.max_width || options.width || 220),
    column_count = Math.max(Math.floor(width / (item_width + item_margin)), 1),
    left = column_count == 1 ? item_margin / 2 : (width % (item_width + item_margin)) / 2,
    lastHeight = 0;
    if (options.max_width) {
        column_count = Math.ceil(width / (item_width + item_margin));
        item_width = (width - column_count * item_margin - item_margin) / column_count;
        left = item_margin / 2;
    }

    for (var i = 0, length = items.length; i < length; i++) {

       var ratio = item_width / items[i].width;
        items[i].width = item_width;
        items[i].height = items[i].height * ratio;
        items[i].position.y = lastHeight + item_margin / 2;
        items[i].position.x = 0;


        lastHeight += items[i].height + (item_margin * 2);
    }

Iterate all the containers and pass the parameters to above function. It will gridify the images/contents in a container. I have used single column per container but you can use multiple columns by using the original code from the gridify.js