Bahar S
Bahar S

Reputation: 429

Changing the color of an array of Images and display them using jQuery or CSS

I am writing a javascript/jquery code that receives a number of png images (base64-encoded, transparent background, black foreground) from a server-side PHP code using Ajax. My Jquery code should then change the color of foreground (black) to a random color and display the images on a random position of the screen. Assume that images are stored in “images[i]” variable (as strings) (“i” is the number of image). I tried using canvas:

var myImg=[];

for (var i = 0; i < NumberOfImages; i++) {
    myImg[i]=new Image();
    myImg[i].src = images[i];

    var w = myImg[i].width;
    var h = myImg[i].height;

    $(display).append("<canvas id='canvas"+i+"' style='width:"+w+"; height:"+h+"; position: absolute; top: "+i*10+"px; left: "+i*10+"px;'></canvas>");
    cnvs = document.getElementById("canvas"+i);
    ctx = cnvs.getContext("2d");

    (function(i){
                myImg[i].onload = function() {
                ctx.drawImage(myImg[i],0,0, w, h);

        var imgd = ctx.getImageData(0, 0, w, h);

        for (j = 0; j <imgd.data.length; j += 4) {
            imgd.data[j]   = theRandomColorR[i];
                imgd.data[j+1] = theRandomColorG[i];
            imgd.data[j+2] = theRandomColorB[i];
        }

        ctx.putImageData(imgd, 0, 0); 
        myImg[i].src = cnvs.toDataURL();
        images[i]=myImg[i].src
        $(display).append(myImg[i]).css({top: i*10,left: i*100, width:i*10, height:i*10});
            //or:
        $(display).append("<img style='width:100px; height:100px; top:200px; left:200px;' src='"+myImg[i].src+"'></img>");
    }              
})(i);

However, this way, I do not have any control on the location or size of the images. Their sizes and colors would be the same and the images would be displayed in the same width and/or height. The reason is probably the usage of “onload” function that makes everything asynchronous. Does anybody know a way I can simply receive the image from Ajax, store it in a variable, change its color using jquery/javascript/CSS and store it to that variable for later use?

Thanks.

Upvotes: 1

Views: 400

Answers (1)

F. M&#252;ller
F. M&#252;ller

Reputation: 4062

I'd rather you use javascript/jQuery only. I once made a gallery-script for myself with javascript it may help you.

http://www.4shared.com/zip/QxWYPWo3/file.html?refurl=d1url

Upvotes: 1

Related Questions