Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A lot of div's in one html

I have an experimental problem. I want to make the image with a lot of div's, div's have a 1px width and height. I got a pixel data of image from the canvas context, create the div and gave value to each div's background-color, it means div's count are equal to image pixels count, but if there is an image for example with 100x56 resolution it's ok, but in case if more than this, browser renders the html very slow. Part of code below

    var fragment = document.createDocumentFragment();
    var data = context.getImageData(0, 0, canvas.width, canvas.height).data;
    for (var i = 0; i < data.length; i += 4) {

        var red = data[i];
        var green = data[i + 1];
        var blue = data[i + 2];

        var div = document.createElement('div');
        div.style.width = '1px';
        div.style.height = '1px';
        div.style.float='left'
        div.style.backgroundColor = 'rgb(' + red + ',' + green + ',' + blue + ')';
        fragment.appendChild(div);

    }
   cnt.appendChild(fragment)

I know this problem is not applicable so much, but I want to know if there is any case to render a lot of elements faster in a browser(I use Chrome) or is it browser-independant?

P.s.: My colleague said "there is no problem in Silverlight like this, you can add even 50000 elements and it will work fine", and I want to give him "my answer"

Thanks

like image 622
Taron Mehrabyan Avatar asked Sep 12 '13 12:09

Taron Mehrabyan


1 Answers

You shouldn't append on each loop. Build a string with the output and then do one append. I'd also remove document.createElement and just build it manually.

Another issue is that you're declaring your RGB variables everytime you loop. Declare any variables outside the loop if possible.

like image 91
Papa Avatar answered Oct 23 '22 03:10

Papa