Home > Software design >  create linear-gradient background from image colors
create linear-gradient background from image colors

Time:11-05

Using Javascript/CSS, I'd like to create linear-background gradients using an image's colors like Youtube is doing in its latest releases (It can be clearly seen when playing any video with bright colors).

The objective is to have a <div> with the background: linear-gradient ... property, and an <img> inside of it. The linear gradient (a radial one) must use the image color palette.

How can I "extract" colors from the image to populate the linear background property?

CodePudding user response:

There are many ways to solve this problem. I add one below.


-html

    <div >
      <img  src="./pic.jpg" />
      <img  src="./pic.jpg" />
    </div>

-css

  .background {
    width: 60px;
    height: 60px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .gradient {
    position: absolute;
    height: 60px;
    width: 60px;
    filter: blur(5px);
  }
  .thumb {
    height: 30px;
    width: 30px;
    position: relative;
    border-radius: 4px;
  }

-result

enter image description here

I'm sorry but your question is difficult to understand.

linear gradient has 2 colors at least.(start,end)

But usually, any picture has lots of colors like your avatar.

So, I think using blur is more convenient.

I hope my answer to help you.

Oh, to control the gradient background, please change blur pixels in your mind.

Good luck.

CodePudding user response:

After a quick bit of digging in dev tools, it appears that YouTube's background "cinematics" lighting works by cross-fading between two oversized canvas elements positioned behind the main video element.

A storyboard of images is provided by the server with a thumbnail snapshot generated for every 10 seconds of the video (You can see these by opening the network monitor in dev tools and looking for M#.jpg?sqp=... images). Each storyboard contains up to 10x10 images, so you'll see a new storyboard requested every ~17 minutes, more if you're scrubbing the timeline in a long video.

These frames are copied in turn onto one of the canvas elements, heavily blurred then slowly faded in to achieve the morphing lighting effect.

That said, if you really did want to sample an image's colours to dynamically build out a linear gradient from it, you could use a similar technique. Create a small canvas and drawImage your source image to it. Then use getImageData to retrieve the canvas' raw pixel data and build your gradient stops from that.

  • Related