简体   繁体   中英

How to GET background color of a particular portion on the html page

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

在此处输入图片说明

Any suggestions?

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

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 ".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM