【问题标题】:why is the y position of text and rect different in svg?为什么svg中text和rect的y位置不同?
【发布时间】:2021-03-28 08:30:38
【问题描述】:

javascript代码的最终结果。

javascript 代码

    tempArr.forEach(function (object, index) {
        barY += 15;
        object.color = `rgba(${Math.random()*255}, ${Math.random()*255}, ${Math.random()*255}, .5)`;

        d3.select('#chart')
            .append('g')
            .attr('class', 'bar');

        d3.select(`#chart g:nth-child(${index+1})`)
            .append('rect')
            .attr('width', `${object['Population'] / 10000000 * 5}`)
            .attr('height', '15')
            .attr('x', '0')
            .attr('y', `${barY}`)
            .style('fill', `${object.color}`)

        d3.select(`#chart g:nth-child(${index+1})`)
            .append('text')
            .text(`${object.Country}, ${object.Population}`)
            .attr('x', `${object['Population'] / 10000000 * 5}`)
            .attr('y', `${barY}`)
            .style('font-size', '10');
    })

我将recttext 标签添加到g 标签中。 你可以看到我使用attr 方法设置yrecttext 标签。 它们在屏幕截图中也是一样的。

但它在视觉上显示的与代码结果不同。

【问题讨论】:

标签: javascript svg d3.js


【解决方案1】:

文本对象中的y位置与所有其他对象不同。

所有其他对象,y是从上到下。但是对于 Text 对象,y=0 是字体设计的基线,y 值从下到上上升。

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 1970-01-01
    • 2015-02-03
    • 2014-06-24
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    • 1970-01-01
    • 2020-09-17
    相关资源
    最近更新 更多