我試圖通過用線性漸變填充筆畫來做車速表。當停止偏移為 0% 時,白線出現在路徑的開頭。我怎樣才能擺脫它?另外,我不確定用線性漸變填充描邊是填充 svg 路徑的最佳選擇。你有更好的想法嗎?
<svg width="196" height="65" viewBox="0 0 196 65" fill="none" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="fillSpeedometer" x1="0" y1="0.5" x2="1" y2="0.5">
<stop offset="0%" stop-opacity="1" stop-color="white" />
<stop offset="0%" stop-opacity="1" stop-color="white" />
<stop offset="0%" stop-opacity="1" stop-color="grey" />
<stop offset="100%" stop-opacity="1" stop-color="grey" />
</linearGradient>
</defs>
<path d="M2 63C3.65579 42.6667 19.0187 2 67.2238 2C115.429 2 171.827 2 194 2" stroke="url(#fillSpeedometer)" stroke-width="3" stroke-linecap="round" />
</svg>

uj5u.com熱心網友回復:
一種常見的方法是通過設定/更改stroke-dasharray屬性來呈現您的當前值/速度。
假設您的“限速”是 300 公里/小時。
將pathLength屬性應用到您的路徑。這樣您就可以輕松地顯示當前速度,例如 50 km/h,如下所示:
stroke-dasharray="150 300"
第二個破折號陣列值將是總速度(或最大范圍值)。
這將確保虛線筆劃有足夠大的間隙(因此您不會看到重復的虛線圖案)。
示例:使用 stroke-daharray
顯示代碼片段
let svgGauges = document.querySelectorAll(".gaugeProgress");
let progress = document.querySelector("#progress");
progress.addEventListener("change", function(e) {
let percent = e.target.value;
if (svgGauges.length) {
svgGauges.forEach(function(gauge, i) {
let currentGauge = svgGauges[i];
let dashGap = gauge.getAttribute("stroke-dasharray").split(" ")[1];
gauge.setAttribute("stroke-dasharray", percent " " dashGap);
});
}
});
#progress,
.speedometer {
display: inline-block;
width: 50%
}
.gaugeProgress {
transition: 0.3s stroke-dasharray;
}
<h3>Speed (km/h)</h3>
<p><input id="progress" type="range" min="0" max="300" step="10" value="150" />
</p>
<svg class="speedometer" viewBox="0 0 196 65" fill="none" xmlns="http://www.w3.org/2000/svg">
<!-- remove stroke-linecap if stroke dash is 0 -->
<style>
[stroke-dasharray^="0 "] {
stroke-linecap: unset;
}
</style>
<defs>
<linearGradient id="fillSpeedometer">
<stop offset="0%" stop-opacity="1" stop-color="orange" />
<stop offset="100%" stop-opacity="1" stop-color="red" />
</linearGradient>
</defs>
<path id="gauge" pathLength="300" d="M2 63C3.65579 42.6667 19.0187 2 67.2238 2C115.429 2 171.827 2 194 2" stroke-width="3" />
<use class="gaugeBG" href="#gauge" stroke="#ccc" stroke-linecap="round" />
<use class="gaugeProgress" href="#gauge" stroke="url(#fillSpeedometer)" stroke-dasharray="50 300" stroke-linecap="round" />
</svg>
如果您使用圓角線帽,您將需要一個額外的 css 規則來防止 value=0 處的可見筆劃。由于 stroke-linecap="round" (或 rect)會擴展您的筆劃破折號,因此您需要像這樣禁用此 stroke-linecap 值:
[stroke-dasharray^="0 "] {
stroke-linecap: unset;
}
這個概念與用于許多儀表/餅圖/甜甜圈圖設計的基本相同......以及svg 線影片。
另請參閱有關 SO 的測量相關問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/432813.html
