简体   繁体   English

从索引中访问 svg 属性。d3.js 中的 html

[英]Access svg attributes from index.html in d3.js

I am trying to replicate this d3.js worldmap:我正在尝试复制此d3.js世界地图:

https://www.d3-graph-gallery.com/graph/backgroundmap_basic.html https://www.d3-graph-gallery.com/graph/backgroundmap_basic.html

However I want to reorganize the code into two parts, index.html and Worldmap.js ,但是我想将代码重组为两部分, index.htmlWorldmap.js

index.html : index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8"/>
    <title>Worldmap</title>
    <script src="https://d3js.org/d3.v6.js"></script>
    <script type="text/javascript" src=Worldmap.js></script>

  </head>

  <body>
    <svg id="my_dataviz" width="400" height="300"></svg>
  </body>
</html>

Worldmap.js : Worldmap.js


// The svg
var svg = d3.select("svg"),
    width = +svg.attr("width"),
    height = +svg.attr("height");

// Map and projection
var projection = d3.geoNaturalEarth1()
    .scale(width / 1.3 / Math.PI)
    .translate([width / 2, height / 2])

// Load external data and boot
d3.json("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/world.geojson",
   function(data){

    // Draw the map
    svg.append("g")
        .selectAll("path")
        .data(data.features)
        .enter().append("path")
            .attr("fill", "#69b3a2")
            .attr("d", d3.geoPath()
                .projection(projection)
            )
            .style("stroke", "#fff")
})

However I get the following error:但是我收到以下错误:

Uncaught TypeError: node is null

selection_attr https://d3js.org/d3.v6.js:1835
<anonymous> Worldmap.js:6

What am I doing wrong here?我在这里做错了什么? I suppose the d3.js cant select the svg attributes from the index.html?我想d3.js不能 select 索引中的svg属性。

  1. Use d3.json as a Promise:使用d3.json作为 Promise:
const url = "https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/world.geojson";
d3.json(url)
  .then(drawMap)
  .catch(err => console.log(err));
  1. Call projection with data:使用数据调用投影:
.attr("d", d => d3.geoPath().projection(projection)(d))

 const svg = d3.select("svg"); const width = parseInt(svg.attr("width")); const height = parseInt(svg.attr("height")); // Map and projection var projection = d3.geoNaturalEarth1().scale(width / 1.3 / Math.PI).translate([width / 2, height / 2]) // Load external data and boot const drawMap = data => { // Draw the map svg.append("g").selectAll("path").data(data.features).enter().append("path").attr("fill", "#69b3a2").attr("d", d => d3.geoPath().projection(projection)(d)).style("stroke", "#fff") }; const url = "https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/world.geojson"; d3.json(url).then(drawMap).catch(err => console.log(err));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.7.0/d3.min.js"></script> <svg width="500" height="500" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM