KJNK
KJNK

Reputation: 9

How would you create a gradient solely with Javascript (no css) that goes from black to white?

Any help? I am new to Javascript. It is just an interesting question I saw online and I am curious possible solutions.

Thanks!

Upvotes: 0

Views: 2276

Answers (2)

Jon Taylor
Jon Taylor

Reputation: 7905

Well black is the hex value #000000 and white the value #FFFFFF, to make things easier we can represent this in decimal values as RGB (0,0,0) and RGB (255,255,255).

You can then use a multitude of approaches varying the colour value as you go in equal amount between R G and B creating a range of gray scale colours.

You could do this on a canvas, you could even do it using a div for each pixel, or you could just use an image if CSS isn't an option. Using divs per pixel is an option but in my opinion really not a very good one.

Pseudo code:

for i = 0 to 255 {
    create div 1/255th of the height of the container and set its background colour to RGB(i,i,i)
}

The problem with this is you will still have to use CSS since styling a DIV can not be done without.

The only possible way to do it completely without CSS would be to use images. If you wanted to dynamically create gradients using images you could even go as far as having images for each grayscale colour and using these in img tags. Again you would not be able to use background images etc since this is CSS too.

Upvotes: 2

nice ass
nice ass

Reputation: 16709

An example using canvas:

var
  canvas = document.getElementById('gradient'),
  context = canvas.getContext('2d'),
  gradient = context.createLinearGradient(0, 0, 0, canvas.height);

gradient.addColorStop(0, '#ffffff');
gradient.addColorStop(1, '#000000');  

context.fillStyle = gradient;
context.fillRect(0, 0, canvas.width, canvas.height);

(demo)

Or by filling the DOM with elements: http://jsfiddle.net/UYxs7/1 (technically this is CSS)

Upvotes: 2

Related Questions