Home > Software design >  How to get the global css background-color at a specific position using javascript
How to get the global css background-color at a specific position using javascript

Time:11-14

I'm looking to get the background color of the viewable page at a specific position.

I want to get the bg color of the page at 70px from the top of the page view, this is because my header/navbar's height is 70px and that's where where I want to get the color of every element that scrolls past that point.

This currently gets the relative position of the container which holds every element that I want to get the color of at that point... (what I mean by, "at that point", is that the bg-color may be a gradient)

$(window).on("scroll", () => {

    let selector = $(".selector")

    // get pixel color at pos y = 70px, pos x does not matter
    let content   = $(".container")
    let rect      = content.get(0).getBoundingClientRect()

    // the navbar is fixed, therefore, the containers relative top pos is 0... so we add 70
    let position  = rect.top   70
    console.log(position)
})

My end goal is to dynamically change the bg-color of the selector element to whatever color from any element that passes the absolute pos of y=70.

As you can see, I'm currently getting the relative y position from the container element.

There are 2 ways that I think could work, yet unsure how to proceed...

  1. Get the pixel color at the absolute pos of y=70
  2. Or the way I've already attempted, which is to get the color at the relative y pos of the container

Please ask for more info if something is not clear, I am aware that this is an irregular task I'm trying to achieve.

CodePudding user response:

I think you are targeting your problem the wrong way. If your end goal is to dynamically change the bg-color of the selector element to whatever color from any element that passes the absolute pos of y=70, I would suggest you write a function that constantly checks the position of every element on your page and if it passes the absolute position of y=70 get the background color and set it to the selector. If this method is conveinent for you but don't know how to apply it comment below and I will help with it.

CodePudding user response:

Consider the following.

$(function() {
  function setBackground(color) {
    $(".page").css("backgroundColor", color);
  }

  function isAtTop(elem, pos) {
    var top = $(elem).offset().top;
    var bottom = top   $(elem).height();
    console.log(top, bottom, pos)
    return (top <= (pos   70) && bottom >= (pos   70));
  }

  $(window).scroll(function(event) {
    var self = $(this);
    $(".content .item").each(function() {
      if (isAtTop(this, self.scrollTop())) {
        setBackground($(this).css("background-color"));
      }
    })
  });
});
body {
  padding: 0;
  margin: 0;
}

.header {
  background-color: white;
  height: 70px;
  width: 100%;
  text-align: center;
  position: fixed;
  top: 0;
}

.content {
  margin-top: 75px;
}

.item {
  width: 340px;
  height: 120px;
  margin: 10px auto;
}

.red {
  background-color: red;
}

.orange {
  background-color: orange;
}

.yellow {
  background-color: yellow;
}

.green {
  background-color: green;
}

.blue {
  background-color: blue;
}

.purple {
  background-color: purple;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="page">
  <div class="header">
    Header
  </div>
  <div class="content">
    <div class="item red">
      Item 1
    </div>
    <div class="item orange">
      Item 2
    </div>
    <div class="item yellow">
      Item 3
    </div>
    <div class="item green">
      Item 4
    </div>
    <div class="item blue">
      Item 5
    </div>
    <div class="item purple">
      Item 6
    </div>
  </div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Using .scrollTop() we can determine how far down the page the User has Scrolled. We then can examine the elements and change the background.

CodePudding user response:

Example using html2canvas and canvas.getImageData

I created an example using html2canvas library. This library will generate an image of the website and store it in a canvas (this canvas we get in a variable and is not visible on the site). With canvas.getImageData you can get the color on the image of a certain pixel at a certain offset.

Example

See a working example at https://833964.playcode.io/

Explanation

The function below renders an image using html2canvas, a printscreen of the website. After the image is loaded by html2canvas we can obtain the color of a certain pixel at a certain offset, see example:

function setColor(offsetY)
{
    html2canvas(screenshotTarget, {scale: '1'}).then((canvas) => {
        var c = canvas.getContext('2d');
        var p = c.getImageData(1, 70   offsetY, 1, 1).data;
        document.getElementById("colorDisplay").style.backgroundColor = "rgb("   p[0] ", " p[1] ", " p[2]   ")";
    });
}

Code

<html>
<head>

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.3.2/html2canvas.min.js"></script>
</head>

<body style="margin: 0px; padding: 0px;">

<div style="width: 100%; position: fixed; background-color: #000;height: 69px;">
    <h1 style="color: #fff; width: 500px; float:left;">Color box (on the right)</h1>
    <span style="width: 30px; height: 30px; float:right" id="colorDisplay"></span>
</div>

<div style="height:550px; background-color:#00ff00;width:100%"></div>
<div style="height:550px; background: linear-gradient(0deg, rgba(34,193,195,1) 0%, rgba(253,187,45,1) 100%);width:100%"></div>
<div style="height:550px; background-color:#0f0f0f;width:100%"></div>
<div style="height:1050px; background-color:#ff0000;width:100%"></div>

<script>
const screenshotTarget = document.body;

function debounce(func, timeout)
{
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => { func.apply(this, args); }, timeout);
  };
}

function setColor(offsetY)
{
    html2canvas(screenshotTarget, {scale: '1'}).then((canvas) => {
        var c = canvas.getContext('2d');
        var p = c.getImageData(1, 70   offsetY, 1, 1).data;
        document.getElementById("colorDisplay").style.backgroundColor = "rgb("   p[0] ", " p[1] ", " p[2]   ")";
    });
}

window.onscroll = debounce(() => setColor(window.pageYOffset), 10);
setColor(0);

</script>
</body>
</html>
  • Related