【发布时间】:2018-06-18 21:37:47
【问题描述】:
如何使用d3.js 将svg 中的高度百分比值转换为百分比宽度值?
我需要这个来在矩形的尖端获得一个方形的svg 元素,这样一个正方形,它的边长等于矩形的高度。这是我需要的,因为我想在svg 中画一个铅笔图标,就像这样:
拥有一个单独的svg 元素来绘制铅笔将允许我通过操纵viewBox 属性值使铅笔具有响应性(而铅笔图标将使用path 元素绘制)。
所以,我面临的问题是高度的百分比代表宽度的不同测量值。例如,高度上的10% 与宽度上的10% 具有不同的含义(换句话说,如果宽度为100,高度为10,则高度为10% 为1,宽度为10% 为10)。
Here 是个小提琴。
debugger;
const svg = d3.select("#drawRegion")
.append("svg")
.attr("width", "100%")
.attr("height", "100%");
svg.append("rect")
.attr("x", "0")
.attr("y", "0")
.attr("width", "100%")
.attr("height", "100%")
.attr("fill", "yellow");
const innerRectX = 10;
const innerRectY = 10;
const innerRectWidth = 80;
const innerRectHeight = 30;
const innerRect = svg
.append("rect");
innerRect
.attr("x", innerRectX + "%")
.attr("y", innerRectY + "%")
.attr("width", innerRectWidth + "%")
.attr("height", innerRectHeight + "%")
.attr("fill", "pink");
const squareSideLength = innerRectHeight;
const squareX = innerRectX + innerRectWidth - squareSideLength;
const squareY = innerRectY;
const mustBecomeASquare = svg
.append("svg");
mustBecomeASquare
.attr("x", squareX + "%")
.attr("y", squareY + "%")
.attr("width", squareSideLength + "%")
.attr("height", squareSideLength + "%")
.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", "100%")
.attr("height", "100%")
.attr("fill", "green");
<div id="drawRegion">
</div>
<script src="https://d3js.org/d3.v5.min.js"></script>
如您所见,绿色的rect 不是正方形。
【问题讨论】:
标签: javascript html css d3.js svg