首页 > 解决方案 > 使用 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不是正方形。

标签: javascripthtmlcssd3.jssvg

解决方案


您可以获得#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");

推荐阅读