繁体   English   中英

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

[英]Getting color value from top row pixels of CSS radial gradient

我有一个用 CSS 创建的圆形径向渐变页面,它从页面底部开始向上辐射。

我的目标是在浏览器中设置元主题颜色以匹配页面顶部的渐变颜色。

问题是渐变顶部的颜色取决于视口的大小。

有没有办法获得页面顶部中心的颜色,所以我可以将主题颜色设置为等于那个颜色?

我的 CSS 渐变定义为:

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

另外,这里有一个 JS Fiddle 显示我的渐变: https : //jsfiddle.net/61ozdy4g/

谢谢!

据我所知,没有办法对通过 CSS 生成的渐变进行采样。

要实现您的要求,请考虑通过Canvas Web API在临时<canvas>元素上再现等效渐变(如您的 CSS 中所定义)。 使用 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);

getImageData()在这个代码片段沙箱中似乎不起作用,但是你可以在这个 jsFiddle 中看到一个工作版本

暂无
暂无

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

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