6

I used Gradient to set the color for my html body background.

CSS:

background: linear-gradient(to top,  #fb4080 10%,#ebb523 22%,#58d27c 40%,#2aff00 52%,#0fd2b7 65%,#6b6dff 80%,#ff05ea 100%);

Now body is filled with multiple colors. Using a javascript how can i get the rgb or hex color code values of a particular portion of the page?

Example:

If i scroll my page, I want to get the color of the top portion of the page(the color inside the highlighted portion not exactly but values near to it) So that i can assign/set that color code to another element on my page like Navigation bar, Menu etc

enter image description here

Any suggestions?

Ramaraju.d
  • 1,301
  • 6
  • 26
  • 46
  • This may help you : http://stackoverflow.com/questions/1887104/how-to-get-the-background-color-of-an-element-using-javascript – Zword Dec 16 '13 at 15:03
  • convert `hsl` to `rgba` with `tinycolor2` - it's what most non-canvas color pickers do – Daniel Lizik Jun 12 '19 at 14:08

2 Answers2

1

I could think of the following options here:

  1. Calculate the gradient in Javascript of which you should be able to get the pixel value How to figure out all colors in a gradient?

  2. Create a hidden canvas with the same gradient and pick the pixel from this canvas http://www.html5canvastutorials.com/tutorials/html5-canvas-linear-gradients/

  3. Use a screenshot library for Javascript and pick the pixel from the screenshot data. Using HTML5/Canvas/JavaScript to take screenshots

Community
  • 1
  • 1
Bas van Dijk
  • 9,933
  • 10
  • 55
  • 91
  • AFAIK, I found 3 is little helpful, But 1 and 2 are explaining how to create a gradient which i already done with it. – Ramaraju.d Dec 16 '13 at 15:24
  • Let me make it more simple to understand, i want the pixel color of any point on the page, Am i clear. Anyway you answer made me think in wide areas I am very thankful to you OSI. – Ramaraju.d Dec 16 '13 at 15:29
  • Then option 3 is the only one suitable. – Bas van Dijk Dec 16 '13 at 15:52
1

Canvas and image objects are the only objects you can read pixel values from.

Instead of using a CSS gradient you can create a canvas behind the body of your page and render the gradient into the canvas. After that you can pick a color from the canvas. A complete example is in my answer to the question "How to set an element's background as the same as a specific portion of web page".

ceving
  • 21,900
  • 13
  • 104
  • 178