使用d3.map()创建D3选择器字典遇错误求助
Hey there, let's break down why you're hitting this error when trying to grab the pitcher's mound bounding box, and how to fix it!
What's Causing the Error?
That error means the code is trying to call getBoundingClientRect() on a null value—aka, it can't find the pitcher's mound element you're targeting. This usually happens for one of two reasons:
- You're trying to access the element before it's been added to the DOM (since D3 loads the SVG asynchronously)
- The ID you're using for the pitcher's mound doesn't match the actual ID in the SVG file
Step 1: Verify the Pitcher's Mound ID in the SVG
First, let's confirm what the actual ID of the pitcher's mound element is. Add a console.log(xml) inside your then callback to print the loaded SVG, then inspect it in your browser's dev tools. You'll be able to see the exact ID of the pitcher's mound shape—don't assume it's what you think it is (case matters too! PitcherMound ≠ pitchermound).
Step 2: Fix the DOM Insertion & Element Timing
You need to make sure the SVG is fully added to the page before you try to grab any elements from it. Here's a revised code snippet that fixes the order and adds safety checks:
d3.xml("https://upload.wikimedia.org/wikipedia/commons/8/89/Baseball_diamond_clean.svg") .then(function(xml) { // First, add the loaded SVG to your page's DOM const svg = xml.documentElement; // Replace 'baseball-field-container' with your actual container ID document.getElementById('baseball-field-container').appendChild(svg); // Now use D3 to select the pitcher's mound (use the ID you confirmed earlier) const pitcherMound = d3.select("#confirmed-pitcher-mound-id").node(); if (pitcherMound) { // Grab the bounding box const bbox = pitcherMound.getBoundingClientRect(); // Store it in your d3.map const fieldBBoxes = d3.map(); fieldBBoxes.set("pitcherMound", { width: bbox.width, height: bbox.height, top: bbox.top, left: bbox.left, right: bbox.right, bottom: bbox.bottom }); console.log("Pitcher's mound BBox stored:", fieldBBoxes.get("pitcherMound")); } else { console.error("Oops! Couldn't find the pitcher's mound element. Double-check the ID!"); } }) .catch(function(err) { console.error("Failed to load the SVG file:", err); });
Key Tips to Avoid This Again
- Always handle async operations correctly: All DOM interactions with the loaded SVG need to happen inside the
thencallback—code outside will run before the SVG finishes loading. - Use D3 selectors for safety:
d3.select("#id")will return an empty selection if the element doesn't exist, instead of throwing an immediate error. Checking if.node()returns a non-null value prevents thegetBoundingClientRect()error. - Inspect the SVG directly: Never guess element IDs—always check the actual SVG structure in dev tools to confirm.
内容的提问来源于stack exchange,提问作者InspectorDanno

