我有這個svg:

我想要一個 HTML 頁面,其中頂部是 SVG,底部是動態高度的 div,它繼續漸變
像這樣:
<svg>...</svg>
<div id="gradient-box" >Gradient box of dynamic height</div>

我知道可以使用帶有顏色、不透明度和度數的 CSS 創建漸變
計算梯度的斜率和角度。請注意,在坐標系中 0deg 指向右側,而 CSS 中的 0deg 指向上方。兩個角度值都是順時針方向。
const slope = (p2.y - p1.y) / (p2.x - p1.x) const angle = (Math.atan2(p2.y - p1.y, p2.x - p1.x) / Math.PI * 180 270) % 360;計算 CSS 中定義的
0%和的位置100%作為坐標。如圖所示,這些點的選擇方式使得對角的顏色值與這兩個值的顏色值完全匹配。連接兩點的線穿過盒子的中心。我將省略所涉及的三角函式,只給出點q1和的結果q2。if (angle == 0) { q1.x = width / 2 q1.y = height q2.x = width / 2 q2.y = 0 } else if (angle == 180) { q1.x = width / 2 q1.y = 0 q2.x = width / 2 q2.y = height } else { q1.x = (width * slope - height) / (slope 1/slope) / 2 q1.y = -(width - height / slope) / (slope 1/slope) / 2 q2.x = width - (width * slope - height) / (slope 1/slope) / 2 q2.y = height (width - height / slope) / (slope 1/slope) / 2 }計算直線上最接近和的兩個點
pp1和。這更多的是數學,而不是拼寫出來,請參考其他類似的問題。pp2p1p2屬于的百分比值
pp1可以pp2作為兩個 CSS 端點之間距離的比例找到。const f1 = (pp1.x - q1.x) / (q2.x - q1.x) || (pp1.y - q1.y) / (q2.y - q1.y); const f2 = (pp2.x - q1.x) / (q2.x - q1.x) || (pp2.y - q1.y) / (q2.y - q1.y);計算
f1和之間每個色標的相對位置f2。const stops = [...gradient.querySelectorAll('stop')].map(stop => { const color = stop.getAttribute('stop-color'); const opacity = stop.getAttribute('stop-opacity'); const offset = parseFloat(stop.getAttribute('offset')); const fraction = offset * (f2 - f1) f1 return {color, opacity, fraction}; });
現在,你終于可以表達 CSS 函式了。最后一個要克服的障礙是將 RGBcolor字串加上opacity值轉換為rgba()符號。您可以為此找到適當的庫。我將假設color-string:
const stopStrs = stops.map(({color, opacity, fraction}) => {
const rgbValue = colorString.get(color);
const opacityValue = parseFloat(opacity);
const rgba = colorString.to.rgb(rgbValue, opacityValue);
return `${fraction * 100}% ${rgba}`
};
const gradientFunction = `linearGradient(${angle}deg, ${stopStrs.join(', ')})`;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/527556.html
標籤:htmlcsssvg
上一篇:陣列到該范圍缺少列的范圍
