使用d3.js将高度值以百分比形式转换为svg中百分比的宽度值

时间:2018-06-17 12:06:08

标签: javascript html css d3.js svg

如何使用d3.js将高度值百分比转换为svg中百分比的宽度值?

我需要这个,以便在矩形的尖端上得到一个方形的svg元素,这样的方形使得它的边长等于矩形的高度。我需要这个,因为我想在svg中绘制一个铅笔图标,就像那样:

enter image description here

有一个单独的viewBox元素用于绘制铅笔,这样我就可以通过操纵path属性值来使铅笔响应(而铅笔图标将使用10%元素绘制)。

因此,我面临的问题是高度的百分比表示宽度的不同测量值。例如,10%的高度与宽度10%的含义不同(换句话说,如果宽度为100,高度为10,则身高10%为1,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");宽度为10)。

Here是一个小提琴。



<div id="drawRegion">

</div>
<script src="https://d3js.org/d3.v5.min.js"></script>
&#13;
rect
&#13;
&#13;
&#13;

正如您所看到的,绿色systemctl start postgresql Job for postgresql.service failed because the control process exited with error code. See "systemctl status postgresql.service" and "journalctl -xe" for details. 不是正方形。

1 个答案:

答案 0 :(得分:0)

您可以使用d3获取#drawRegion的宽度和高度。使用这些值绘制相同宽度和高度的rect

const width = parseInt(d3.select("#drawRegion").style("width"));
const height = 150;

const svg = d3.select("#drawRegion")
    .append("svg")
    .attr("width", width)
    .attr("height", height);

svg.append("rect")
    .attr("x", "0")
    .attr("y", "0")
    .attr("width", "100%")
    .attr("height", "100%")
    .attr("fill", "yellow");

const innerRectHeight = 0.3 * height;
const innerRectWidth = width - ((0.2 * width) + innerRectHeight);
svg.append("rect")
    .attr("x", "10%")
    .attr("y", "10%")
    .attr("width", innerRectWidth)
    .attr("height", innerRectHeight)
    .attr("fill", "pink");

const greenRectPos = innerRectWidth + (0.1 * width);
svg.append("rect")
    .attr("x", greenRectPos)
    .attr("y", "10%")
    .attr("width", innerRectHeight)
    .attr("height", innerRectHeight)
    .attr("fill", "green");