javascript - 使用 d3.js 将百分比的高度值转换为 svg 中的百分比宽度值
问题描述
svg
在using中,如何将百分比的高度值转换为百分比的宽度值d3.js
?
我需要这个才能在矩形的尖端获得一个方形svg
元素,这样一个正方形,它的边长等于矩形的高度。这是我需要的,因为我想像这样画一个铅笔图标svg
:
拥有一个svg
用于绘制铅笔的单独元素将允许我通过操作属性值来使铅笔响应viewBox
(而铅笔图标将使用该path
元素绘制)。
所以,我面临的问题是高度的百分比代表宽度的不同测量值。例如,10%
in height 与 in width 的含义不同10%
(换句话说,如果 width 为 100,height 为 10,则10%
in height 为 1,10%
in width 为 10)。
这是一个小提琴。
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
不是正方形。
解决方案
您可以获得#drawRegion
使用 d3 的宽度和高度。使用这些值绘制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");
推荐阅读
- sql - SQL Server 过滤唯一的最新日期和付款
- wix - 如何在 AppData 中创建嵌套文件夹
- python - 按索引访问 coo_matrix 的 TypeError
- android - Android Studio:基于调试而不是发布
- ruby - Ruby脚本问题
- android - 我的 Listview 小部件中没有显示数据
- java - UDP 多播在 2 台不同的 PC 中不起作用
- bash - 在bash中迭代地打印csv中现有文本下方的文本
- apache-nifi - 如何通过动态表名从rest api调用执行sql
- python - ImportError:libkfusion.so:无法打开共享对象文件:没有这样的文件或目录