canvas fun SO quetion 20297032

http://stackoverflow.com/questions/20297032/how-to-build-a-preview-image-by-stacking-transparent-images-based-on-form-select/20450484#20450484

by Gerald Gillespie

HTML

<canvas id="left" width="450" height="200"></canvas>
<canvas id="right" width="450" height="200"></canvas>
<div id="colors">click canvas to cycle these colors (yes these choices are ugly)
    <div class="colors yellow">&nbsp;</div>
    <div class="colors blue">&nbsp;</div>
    <div class="colors green">&nbsp;</div>
    <div class="colors red">&nbsp;</div>
</div>

CSS

#left {
    /* use css to apply background and colors.  pngs need transparency and the texture portion needs shape so they don't overlap like in my example */
    background:url(http://farm4.static.flickr.com/3085/2634310431_ccae90c2b1_o.png);
}
#right {
    position:absolute;
    top:100 px;
    left:200px;
    background:url(http://farm4.static.flickr.com/3085/2634310431_ccae90c2b1_o.png);
}
.yellow {
    background-color : yellow
}
.blue {
    background-color : blue
}
.green {
    background-color : green
}
.red {
    background-color : red
}

JavaScript

var counter, alpha; // globals for our test
    alpha = 0.4 
    counter = 0
    
        function createCanvas(id, color, alpha) {
            var context, canvas;
            
            canvas = document.getElementById(id);
            context = canvas.getContext('2d');
            context.clearRect(0, 0, canvas.width, canvas.height); // clear canvas first
            context.globalAlpha = alpha || 0.4; // transparency could be dynamic
            context.beginPath();

            switch (id) { // add a case for each piece
                case 'left':

                    context.moveTo(0, 0);
                    context.lineTo(0, 200);
                    context.lineTo(400, 200);
                    context.arc(200, 100, 75, 50, 50);
                    break;
                case 'right':
                    context.moveTo(0, 0);
                    context.lineTo(200, 200);
                    context.arc(200, 100, 75, 50, 50);
                    break;
            }
            context.closePath();
            context.lineWidth = 0;
            context.fillStyle = color || '#8ED6FF'; // dynamic color from provided list
            context.fill();

        };

    // have some kind of color selector
    $('body').on('click', 'canvas', function () {
        console.log(this, counter);
        var newShapeColor = $('div.colors:eq(' + counter + ')').css('background-color');
        createCanvas($(this).attr('id'), newShapeColor, alpha);
        counter = (counter < 3) ? counter + 1 : 0;
    });

    //initialize peices
    createCanvas('left');
    createCanvas('right');
    // add other peices here.