Search code examples
javascriptjqueryhtmlcsscss-shapes

Grid with clicable irregular shapes


I'm having a bit of trouble here to develop this functionality since it must work on IE9+ so css clip-path is not an option ( http://caniuse.com/#feat=css-clip-path ).

The issue:

  • I need to create a grid composed of 6 elements.
  • Each element is an image.
  • The images can be different according to user answers before getting to the grid page.
  • Eeach element / image must be clicable and will acquire a "selected" class that will overlay div with text and background image.

image:

enter image description here

What is the best way to achieve this?


Solution

  • One way to do this could be to save out each combination of the six images you require into one big image. Then, depending on the user's answer combination, you insert the corresponding image as a background-image of a div. You then overlay click-able hotspots within the same div that roughly correlate to the dividing edges.

    This may however not be the most practical solution and largely depends on how many answers/images you are dealing with.

    Alternatively you could draw SVG shapes and set their fills to the images you require.

    I can recommend Raphael.js as a starting point. You should be able to find what you need in the documentation

    Another option would be to use HTML5 canvas: http://jsfiddle.net/julienbidoret/GKP7X/1/

    (credit goes to julienbidoret for the jsfiddle)

    Javascript:

    var canvas = document.getElementById('c');
    var ctx = canvas.getContext('2d');
    var img = document.createElement('IMG');
    
    img.onload = function () {
    
        ctx.save();
        ctx.beginPath();
        ctx.moveTo(20, 0);
        ctx.lineTo(240, 0);
        ctx.lineTo(220, 240);
        ctx.lineTo(0, 240);
        ctx.closePath();
        ctx.clip();
        ctx.drawImage(img, 0, 0);
        ctx.restore();
    }
    
    img.src = "http://upload.wikimedia.org/wikipedia/commons/2/2b/Clouds.JPG";
    

    HTML:

    <canvas id="c" width="300" height="300" ></canvas>
    

    Both SVG and canvas are supported in IE9.