You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

D3报错transition is not a function 六边形描边动画代码求助

Fixing "d3 transition is not a function" Error for Hexagon Stroke Animation

Let's break down why you're hitting this error and how to get your hexagon stroke animation working smoothly.

Common Causes & Solutions

1. Incorrect D3 Reference or Import

The root issue is almost always how you're accessing D3's transition method. Let's troubleshoot this first:

  • If you're using this.d3.transition(), confirm you actually assigned the D3 library to this.d3 in your class. If not, switch to using the global d3 object (if loaded via script tag) or a properly imported reference.
  • For ES module environments (like React/Vue with imports):
    • Use a full import to ensure all D3 modules (including transition) are available:
      import * as d3 from 'd3';
      
    • Or use partial imports if you want tree-shaking support—just make sure to explicitly include transition:
      import { transition, easeLinear } from 'd3';
      
  • If loading via a script tag, ensure you're using the complete D3 library (not a stripped-down subset):
    <script src="https://d3js.org/d3.v7.min.js"></script>
    

2. Corrected Animation Code

Once you've fixed the transition reference, here's the complete, working version of your hexagon stroke animation (filling in the truncated parts of your original code):

const hexagon = this.hexagonSVG.append('path') 
  .attr('id', 'active') 
  .attr('d', lineGenerator(<any>hexagonData)) 
  .attr('stroke', 'url(#gradient)') 
  .attr('stroke-width', 3.5) 
  .attr('fill', 'none');

const totalLength = hexagon.node().getTotalLength();

// Use d3.transition() directly (adjust if you need a scoped D3 instance)
const hexTransition = d3.transition() 
  .duration(DASH_ANIMATION) 
  .ease(d3.easeLinear);

// Set up initial dash state to hide the stroke, then animate it in
hexagon 
  .attr('stroke-dasharray', `${totalLength} ${totalLength}`) 
  .attr('stroke-dashoffset', totalLength) // Start with full offset (hidden stroke)
  .transition(hexTransition)
  .attr('stroke-dashoffset', 0); // Animate to 0 to "draw" the stroke

Key Animation Details:

  • The initial stroke-dashoffset set to totalLength ensures the entire stroke is hidden at the start.
  • Transitioning the offset to 0 creates the "drawing" effect along the hexagon path.
  • Make sure DASH_ANIMATION is defined as a numeric value (e.g., 1500 for a 1.5-second animation).

Final Quick Checks

  • Verify your D3 version is v4 or newer (older versions used different transition syntax).
  • Confirm this.hexagonSVG is a valid D3 selection (not a raw DOM element) so the append() method works as expected.

内容的提问来源于stack exchange,提问作者Jeremy Yung Hau Ng

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:08:23