Many div in one html

I have an experimental problem. I want to make an image with a lot of div 's, divs have 1px width and height . I got the image pixel data from the canvas context , create a div and gave a value for each div background-color , this means that the div count is equal to the number of pixels in the image, but if there is an image, for example, with a resolution of 100x56, this is normal, but in case, if it is more, the browser makes html very slow. Code piece 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 make many elements faster in the browser (I use Chrome) or is it browser independent?

Ps: My colleague said: “There is no such problem in Silverlight, you can even add 50,000 elements and it will work fine”, and I want to give it “my answer”

thanks

+6
source share
2 answers

You do not have to join every cycle. Create an output line, and then add it. I will also remove document.createElement and just create it manually.

Another problem is that you declare your RGB variables every time you loop. Declare any variables outside the loop, if possible.

+3
source

If the experiment should use only html elements, I recommend that you get the base 64 image from the canvas, and then add it to the img tag.

 var src = canvas.toDataURL(); var img = document.getElementsById('image_id'); img.src = src; img.onload = function () { console.log('image loaed'); }; 

If you need to create a dynamic image

 var src = canvas.toDataURL(); var newImg = document.createElement("img"); newImg.src = src; img.onload = function () { document.body.appendChild(newImg); }; 
0
source

Source: https://habr.com/ru/post/953700/


All Articles