我正在使用一個視圖框來將資料坐標映射到 SVG 顯示中。
所有的資料似乎都與視圖框對齊(我使用紅色邊框來顯示視圖框的邊界,使用藍色邊框來顯示 SVG 的邊界),但是軸線在兩個維度上正好偏移了 0.5。
有趣的是,刻度線被正確地錨定在軸的位置(盡管略有偏移),只有軸線被偏移。
我嘗試了舊版本的d3(我回到了3年前的5.3.0的幾個版本,但都有相同的行為)
我可以看到,在d3中,有很多人都是在使用 "小 "字。
我可以看到在結果的HTML輸出中,軸的path規范是不正確的,但不知道為什么 - 例如,對于y軸,
<path class="domain"/span> stroke="currentColor"/span> d="M-0. 2,0.5H0.5V12.5H-0.2"></path>
實際上應該是
<path class="domain" stroke=" currentColor" d="M-0。 2,0.0H0.0V12.5H-0.2"></path>
而且刻度線也被translated錯誤地多了一個0.5的y偏移(這個應該不被轉換或者使用translate(0,0)):
<g class="tick" opacity="1" transform="translate(0,0。 5)">< line stroke="currentColor"/span> x2="-0. 2"></line><。 text fill="currentColor"/span> x="-0。 35000000000000003" dy="0.32em">0</text> /span></g>
復制測驗案例:
<! DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"><meta charset="utf-8" >
<style> /*設定CSS */
body { 字體。12px Arial;}
path {
填充:無。
}
rect {
填充。#bbb;
行程。#222;
描邊寬度: 0.05;
}
.axis path,
.軸線 {
填充:無。
筆觸:灰色。
筆畫寬度:0.1。
形狀渲染: crispEdges;
}
.debug {
填充:無。
}
.debug.red {
筆觸。#f44;
}
.debug.blue {
筆觸。#44f;
}
</style>
</head><body>
<!--加載d3.js庫-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.0.1/d3.min.js"></script>
<script>
var data = [[0,0], [3,3], [10,10] ]
var width = 12
var height = 12
const margin = 1.5
const graph = d3.select("body")
.append("svg")
.attr("viewBox", d => `-${margin} ${width 2*margin}. -${margin} ${width 2*margin} ${height 2*margin}`)
.attr("寬度", 600)
graph.append("rect")
.attr("class", "debug blue")
.attr("x", -margin)
.attr("y", -margin)
.attr("width", width 2 * margin)
.attr("高度", 高度 2 * margin)
graph.append("rect")
.attr("class", "debug red")
.attr("x", 0)
.attr("y", 0)
.attr("width", width)
.attr("高度", 高度)
const scaleY = d3.scaleLinear().domain([0, height]).range([0, height])
const axisY = d3.axisLeft(scaleY).tickSize(0.2).tickPadding(0.1*margin)
const scaleX = d3.scaleLinear().domain([0, width]).range([0, width])
const axisX = d3.axisBottom(scaleX).tickSize(0.2).tickPadding(0.1*margin)
graph.append("g")
.attr("class", "axis")
.call(axisY)
graph.append("g")
.attr("class", "axis")
.attr("transform", d => `translate(0,${height})`)
.call(axisX)
const plot = graph.selectAll("plot")
.data(data)
.輸入()
.append("rect")
.attr("x", d => { console.log(d); return d[0]})
.attr("y", d => d[1])
.attr("寬度", 0.8)
.attr("高度", 0.8)
</script>
</body></html>
uj5u.com熱心網友回復:
大約在d3v4或5的時候,D3開始為軸刻度加入了一個偏移量:
Safari經常在形狀渲染方面出錯:crispEdges,即使是畫一條兩像素寬的線 即使筆觸寬度是一個像素,也會繪制一條兩像素寬的線。還有。 在坐標被四舍五入的常見情況下,使用一個 的情況下,使用半像素的偏移應該可以產生清晰的邊緣,即使沒有 形狀渲染。
我認為我們應該對坐標使用基于零的索引,例如 y = 0 表示最上面的像素,x = 0 表示最左邊的像素,因此在 x 和 y 中的偏移量為 0.5(而不是 -0.5)。(來源)
這個讓人猝不及防。
我不確定最初的實作,但從d3v7開始,你可以用axis.offset()來修改偏移量:
如果指定了偏移量,則將偏移量設定為指定的值,單位為 像素,并回傳該軸。如果沒有指定偏移量,則回傳 當前的偏移量,在設備像素比大于1的設備上默認為0,而在設備像素比為0.5的設備上默認為0。 大于1的設備,默認為0,否則為0.5px。這個默認的偏移量可以確保在低解析度的設備上有清晰的 邊緣。
因此,解決方案很可能是轉移到 d3v7 并使用 axis.offset(0)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/320668.html
標籤:
上一篇:多線圖的SVG圖例d3v6
