首页 > 解决方案 > 图像未显示在附加的 d3 甘特图中

问题描述

我正在尝试在甘特图水平条中附加一些图像,但它没有显示。但是标签被附加在rect标签内。这是代码

const start_date = "2020-01-15";
const end_date = "2020-05-05";

    const MARGIN = {
        left: 50,
        right: 50,
        top: 50,
        bottom: 50
    }
  
    const svg = d3.select('.graph').append('svg')
    // console.log(svg)
    const width = 800
    const height = 600

    const ticks = ['task1', 'task2', 'task3', 'task4', 'task5', 'task6'];
  
    const x = d3.scaleTime().domain([new Date(start_date), new Date(end_date)]).range([0, (width - (MARGIN.left + MARGIN.right))])
    const y = d3.scaleBand()
                    .domain(ticks)
                    .range([0, 400])
                    // .range([0, 50,100, 150, 200, 250, 300, 350,height])
    const  X = v => {
            const minDate = d3.min(v, d => new Date(d.initDate))
            const maxDate = d3.max(v, d => new Date(d.endDate))
            return d3.scaleUtc().domain([minDate, maxDate]).range([MARGIN.right, width - MARGIN.left]);
            }
    const x_axis = d3.axisTop(x).ticks(6);
    const y_axis = d3
                    .axisLeft(y)
                    .ticks(6)
                    .tickFormat(function(d, i){return ticks[i]})
                    .tickSize(15);
  
    svg.attr('width', width).attr('height', height).attr('viewBox', `0 0 700 800`)
    let chart = svg.append("g").attr('class', 'chart-holder').attr('transform', `translate(50,50)`);
  
    chart
      .append("g")
        .attr('class', 'x axis')
        .attr("transform", "translate(0,50)")
        .call(x_axis);
  
    chart
      .append("g")
        .attr('class', 'y axis')
        .attr("transform", "translate(0, 50)")
        .call(y_axis);

    chart
         .selectAll('rect')
        .data([...this.state.data])
        .enter()
        .append('rect')
        .attr('height', 40)
        .attr('x', function(d){
            return x(new Date(d.initDate))
        })
        .attr('y', function(d, i){
            return y(d.name);
        })
        .attr('width', function(d, i){
            return x(new Date(d.endDate)) - x(new Date(d.initDate))
        })
        .attr('rx', 17)
        .attr('ry', 17)
        .attr('fill', "blue")
        .attr('transform', `translate(50, 60)`)
        .append('image')
        .attr("src", "https://miro.medium.com/max/1000/1*tv9pIQPhwumDnYBfCoapYg.jpeg")
        .attr("width", 30)
        .attr("height", 30)

以及我已经尝试过的事情

xlink:href代替href

svg:image代替image

标签: javascriptreactjsd3.js

解决方案


您不能在 . 替换为 ,然后追加和下

const items = chart.selectAll('g.item').data(...).enter().append('g').classed('item', true);

items.append('rect')...

items.append('image')...


推荐阅读