如何使用d3和Ajax动态地将文本附加到svg?

时间:2017-07-11 19:42:50

标签: javascript jquery ajax d3.js svg

我对Ajax调用一无所知,已经阅读了几个小时,但是所有的教程都提到了load方法和一个像click一样的监听器。

我有一个函数(drawThreat)在我的svg上添加了一些图标(fontawesome),有一堆x和ys的json文件,我需要做的就是有一个运行这个函数的ajax调用每隔5秒在json文件中显示所有x和y,并更新页面上的svg元素。这是功能:

function drawThreat (x, y){
  var canvas = d3.select("#map")
                 .append("svg")
                 .attr("width", 500)
                 .attr("height", 500)
                 .attr("id", "Threat");

  var Threat = canvas.append('svg')
                    .append('text')
                    .attr('text-anchor', 'middle')
                    .attr('dominant-baseline', 'central')
                    .attr("x", x)
                    .attr("y", y)
                    .attr("class", "threat")
                    .style('font-family','FontAwesome')
                    .style('font-size','20px')
                    .style('fill', 'red')
                    .text(function (d) {
                    return '\uf2be'
                    });
        return Threat
};

任何帮助都将被赞赏:)即使它是您找到与该问题相关的教程的链接。到目前为止,我看了6或7个教程,没有运气。

1 个答案:

答案 0 :(得分:1)

如果我理解你的需要,你基本上可以有类似下面的代码:

var dataFileUrl = "url-to-your.json";          // assign the url to a variable
var canvas = d3.select("#map")                 // get a ref from the SVG element
                  .append("svg")               // you might want to define it only one time
                      .attr("width", 500)
                      .attr("height", 500)
                      .attr("id", "Threat");


var updateInterval = setInterval(function(){  
    d3.json(dataFileUrl , function (jsonData) { // AJAX call
        drawThreat(jsonData);                   // calls main function
    });                                    
},5000);                                        // every 5 * 1000ms 


function drawThreat (jsonData){ 
    canvas.selectAll('text.threat').remove();  // makes sure we don't have old icons
    canvas.selectAll('text')
        .data(jsonData)                        // for each set in json
            .enter()
                .append('text')                // create a text and append it to svg canvas
                .attr("class", "threat")       // with class of threat
                .attr("x", function (d) {  return d[0]; })  // first element of each set
                .attr("y", function (d) {  return d[1]; })  // second element of each set
                .text('\uf2be');                

 };

减少js代码我建议使用CSS添加样式和属性:

.threat{                   
    text-anchor:middle;
    dominant-baseline:central;
    font-family:FontAwesome;
    font-size:20px;
    fill:red;
}

您还可以在此处看到它:https://codepen.io/FaridNaderi/pen/awPBwm

希望它能帮助你明白这一点。