简体   繁体   English

从 CSS 径向渐变的顶行像素获取颜色值

[英]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.我有一个用 CSS 创建的圆形径向渐变页面,它从页面底部开始向上辐射。

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:我的 CSS 渐变定义为:

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

Also, here is a JS Fiddle showing my gradient: https://jsfiddle.net/61ozdy4g/另外,这里有一个 JS Fiddle 显示我的渐变: https : //jsfiddle.net/61ozdy4g/

Thanks!谢谢!

As far as I'm aware, there's no way to sample a gradient generated via CSS.据我所知,没有办法对通过 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 .要实现您的要求,请考虑通过Canvas Web API在临时<canvas>元素上再现等效渐变(如您的 CSS 中所定义)。 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:使用 Canvas Web API 的getImageData()方法,然后您可以对位于画布元素顶部/中心位置的像素进行采样,以查找渐变中该点处的rgb()颜色并设置其格式:

 // 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 getImageData()在这个代码片段沙箱中似乎不起作用,但是你可以在这个 jsFiddle 中看到一个工作版本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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