簡體   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