Cut image into cells and flip each cell.

This demo demonstrates how to cut some image into cells and allow to flip each cell on click.

by viphalongpro

HTML

<div class='canvas'>
</div>

CSS

.canvas {
    background:url('http://placekitten.com/500/300');
    width:500px;
    height:300px;
}
.cell {    
    float:left;    
    position:relative;
    cursor:pointer;
}
.cell > .front {            
    -webkit-backface-visibility: hidden; 
    backface-visibility:hidden;
    -webkit-transform-style:preserve-3d;
    transition:all 1s;
}
.cell:not(.flipped) > .back {
    -webkit-transform:rotateY(180deg);
}
.cell.flipped > .front {
    -webkit-transform:rotateY(180deg);
}
.back {
    background:pink;
}
.cell > .back {
    position:absolute;
    text-align:center;
    font-size:30px;
    color:red;    
    left:0;
    top:0;    
    transition:all 1s;    
}
.cell > .back:before {
    content:'';
    display:inline-block;
    height:100%;
    vertical-align:middle;
}
.cell > * {
    border: 1px solid orange;    
    box-sizing:border-box; 
    width:100%;
    height:100%;
}

JavaScript

//get the canvas
var canvas = $('div.canvas');
var backgroundImage = canvas.css('background-image');
//remove the background from canvas
canvas.css('background-image','none');
//number of columns and rows
var col = 8;
var row = 4;
var colWidth = canvas.width() / col;
var rowHeight = canvas.height() / row;
//loop through the cells
for(var i = 0; i < row; i++){
    for(var j = 0; j < col; j++){
        //append new cell to canvas
        var cell = $("<div class='cell flipped'><div class='back'>?</div><div class='front'></div></div>")
                   .width(colWidth).height(rowHeight).appendTo(canvas);
        //set the background for the cell
        //note that calculate the em unit for more flexible
        //font-size
        cell.find('.front')
            .css('background',backgroundImage)
            .css('background-position', -(j * colWidth) + 'px ' + -(i * rowHeight) + 'px');
        //register click handler for the cell
        cell.click(function(){$(this).toggleClass('flipped')});
    }
}