0

What's the best way to colorize the inner area of div with random colors?

Let's say we have <div style="width:200px; height:200px;">colorize the whole rectangle</div>

The question I asked previously Color a pixel in the div was about one pixel only. What about the all pixels?

As far as I believe there is no solution with css only. So, javascript is a perfect solution. Please no jQuery, unless it doesn't affect the performance. Performance counts.

So, the background-color:red; is not a solution as it paints with one color only. I want to be able to choose a color for any (m,n) pixel in the div.

Thank you.

Community
  • 1
  • 1
Haradzieniec
  • 9,086
  • 31
  • 117
  • 212
  • 1
    So like a gradient of some sort? http://www.w3schools.com/css/css3_gradients.asp – Dan Feb 25 '14 at 15:00
  • Thank you but UNFORTUNATELY that's not I'm looking for. That's an option if you want a gradient, but not when you want to draw a light "image" in the div. – Haradzieniec Feb 25 '14 at 15:11

2 Answers2

2

I made a demo for this kind of requirement here: http://jsfiddle.net/7FMD2/3/.

The solution can be broken down in the following steps:

  1. Allow passing explicit colors for specific areas in the target element
  2. Generate random colors for all areas missing a specific color setting
  3. Generate all the elements needed in a DocumentFragment for performance with explicitly defined styles, including position: absolute
  4. Set the target element's position to position: relative and append the DocumentFragment

Usage

var element = document.getElementById('rainbow');
new Rainbow(element, options).initialize();

Options

For the sake of it I included the following options on Rainbow

  • forced: Takes a nested object with pixel coordinates as keys and the forced colors as value: forced: { 1: { 0: '#000000', 20: '#fffff' } } will force pixel x:1,y:0 to be black and pixel x:1,y:20 to be white
  • pixelSize: Defines the size of one pixel in your target div. The fiddle uses a setting of 10 for pixelSize, which causes every block of color to be 10px in height and 10px in width.

Note

This can get very expensive for large target elements as every single block of color has its own element. Especially in older browsers this can hit performance pretty hard. You'd probably be better off with generating an image via canvas as Andreas Møller suggests or with some simple server side script providing the image for you to use as background-image.

marionebl
  • 3,342
  • 20
  • 34
0

There is no good solution using only html, since the markup would be quite heavy.

I would recommend using a canvas. Check out this post for reprence: Drawing a dot on HTML5 canvas

Community
  • 1
  • 1
Andreas Møller
  • 839
  • 5
  • 9