简体   繁体   中英

Getting color value from top row pixels of CSS radial gradient

I have a page with a circular radial gradient created with CSS, that starts out at the bottom of the page and radiates upwards.

My goal is to set the meta theme color in the browser to match the colour of the gradient at the top of the page.

The problem is that the color that the gradient has at the top is dependent on the size of the view-port.

Is there any way to get the color of the top center of the page, so I can set the theme color equal to that?

My CSS gradient is defined as:

background: radial-gradient(circle at bottom center, #C25351, #EC991A 100%)

Also, here is a JS Fiddle showing my gradient: https://jsfiddle.net/61ozdy4g/

Thanks!

As far as I'm aware, there's no way to sample a gradient generated via CSS.

To achieve what you require, consider reproducing the equivalent gradient (as defined in your CSS) on a temporary <canvas> element via the Canvas Web API . Using the Canvas Web API's getImageData() method, you can then sample the pixel located at the top/center location of the canvas element to find and format the rgb() color at that point in the gradient:

 // Create temporary canvas and get context for rendering const canvas = document.createElement('canvas'); var ctx = canvas.getContext("2d"); const width = document.body.clientWidth; const height = document.body.clientWidth; const halfWidth = Math.floor(width * 0.5); const halfHeight = Math.floor(height * 0.5); const gradientRange = Math.sqrt(width ** 2 + height ** 2); // Size the canvas to match viewport canvas.width = width; canvas.height = height; // Create a gradient for the fill var grd = ctx.createRadialGradient(halfWidth, height, 0, halfWidth, height, gradientRange); grd.addColorStop(0, "#C25351"); grd.addColorStop(1, "#EC991A"); // Render gradient across whole fill covering canvas ctx.fillStyle = grd; ctx.fillRect(0, 0, width, height); // Sample pixel at top center of canvas and format rgb string var pixel = ctx.getImageData(halfWidth, 0, 1, 1).data; var color = `rgb(${pixel[0]}, ${pixel[1]}, ${pixel[2]})` alert(color) // Add the canvas to document for visual inspection (not // required, just included for snippet) document.body.appendChild(canvas);

The getImageData() appears not to work in this code snippet sandbox, however you can see a working version in this jsFiddle

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