我一直在使用 SVG 創建離散圖例顏色選擇器。我希望顏色選擇器 div 具有固定的寬度,并且內容(svg 單元格)應該適合基于 div 的寬度。請注意,由于代碼很長,我只是粘貼幾行代碼。
var cellWidth = 22;
var cellHeight = 22;
// 這不是完整的代碼
const selectedLegend = select(divRef.current);
selectedLegend
.append("div")
.append("svg")
.style("margin-top", "13px")
.style("margin-left", "137px")
.style("margin-right", "35px")
.style("width", "100%")
.style("height", "25px")
.style("background", "red")
// 填充顏色的代碼
g.selectAll("g.legendCells")
.append("rect")
.attr("height", cellHeight)
.attr("width", cellWidth)
.style("fill", function (d: Record<string, unknown>) {
return d["color"];
// 直線對齊單元格
g.selectAll("g.legendCells")
.attr("transform", function(d: any, i: number) {
return "translate(" (i * cellWidth) ",0)" })

我想讓圖例占據全角,它必須覆寫整個背景紅色。
更準確地說,我想要如下所示的東西,矩形單元格必須適合恒定寬度。

uj5u.com熱心網友回復:
如果您沒有在 svg 上設定寬度并使用該viewBox屬性,則 SVG 只會填充整個空間。
更新
影像應拉伸:始終寬度應為 100%,高度應固定(此處為 50 像素)。要使影像拉伸,請將preserveAspectRatio屬性設定為“無”。
#container svg {
display: block;
}
<div id="container">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 2"
width="100%" height="50" preserveAspectRatio="none">
<rect width="20" height="2" fill="#eee"/>
<rect x="0" y="0" width="1" height="1" fill="#000"/>
<rect x="1" y="0" width="1" height="1" fill="#111"/>
<rect x="2" y="0" width="1" height="1" fill="#222"/>
<rect x="3" y="0" width="1" height="1" fill="#333"/>
<rect x="4" y="0" width="1" height="1" fill="#444"/>
<rect x="5" y="0" width="1" height="1" fill="#555"/>
<rect x="6" y="0" width="1" height="1" fill="#666"/>
<rect x="7" y="0" width="1" height="1" fill="#777"/>
<rect x="8" y="0" width="1" height="1" fill="#888"/>
<rect x="9" y="0" width="1" height="1" fill="#999"/>
<rect x="10" y="0" width="1" height="1" fill="#aaa"/>
</svg>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/451856.html
