javascript - 使用 d3.js 将以百分比表示的高度值转换为 svg 中以百分比表示的宽度值

标签 javascript html css d3.js svg

如何使用 d3.jssvg 中将以百分比表示的高度值转换为以百分比表示的宽度值?

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

enter image description here

有一个单独的 svg 元素来绘制铅笔将允许我通过操纵 viewBox 属性值使铅笔响应(而铅笔图标将使用path 元素)。

所以,我面临的问题是高度的百分比表示宽度的不同测量值。例如,高度的 10% 与宽度的 10% 具有不同的含义(换句话说,如果宽度为 100,高度为 10,则 10% 高度为 1,10% 宽度为 10)。

Here是一把 fiddle 。

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 不是正方形。

最佳答案

您可以使用 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");

关于javascript - 使用 d3.js 将以百分比表示的高度值转换为 svg 中以百分比表示的宽度值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50896461/

相关文章:

php - ipad 网站上的电话号码消失了

html - 在不使用插件的情况下在 Umbraco 中创建动态图像 slider

javascript - 在 angularjs 中运行 jquery 代码的最佳方式是什么?

html - 我的背景图片总是在底部被截断?

javascript - 函数声明 vs 函数定义 JS

javascript - jsStringFormat() 和带有 JSON 的撇号

javascript - JS脚本中的执行顺序

javascript - 使用自定义上一个和下一个按钮 (FullCalendar)

css - 使用CSS在鼠标悬停时更改侧面菜单的背景图像

Css改变流体图像的纵横比