【问题标题】:Getting color value from top row pixels of CSS radial gradient从 CSS 径向渐变的顶行像素获取颜色值
【发布时间】:2019-04-24 07:16:07
【问题描述】:

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

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

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

有什么方法可以获取页面顶部中心的颜色,所以我可以设置主题颜色等于那个?

我的 CSS 渐变定义为:

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

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

谢谢!

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    据我所知,无法对通过 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() 似乎在此代码 sn-p 沙箱中不起作用,但是您可以看到一个工作版本 in this jsFiddle

    【讨论】:

      猜你喜欢
      • 2014-08-12
      • 2016-02-03
      • 2012-03-15
      • 1970-01-01
      • 2012-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多