【问题标题】:Convert the height value in percents to the width value in percents in svg using d3.js使用 d3.js 将百分比的高度值转换为 svg 中的百分比宽度值
【发布时间】:2018-06-18 21:37:47
【问题描述】:

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

我需要这个来在矩形的尖端获得一个方形的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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2012-10-17
      • 2010-10-17
      • 2013-08-23
      • 2013-03-13
      • 1970-01-01
      • 1970-01-01
      • 2014-02-17
      • 2012-06-24
      • 1970-01-01
      相关资源
      最近更新 更多