Disabling all D3 animations (for testing)

前端 未结 4 1505
旧巷少年郎
旧巷少年郎 2020-12-30 00:36

I\'m looking for a D3 equivalent to jQuery.fx.off = true.

Say you are writing tests (with Mocha, QUnit, etc.) for an app that uses D3. The app has some D3 animations

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-30 01:11

    I do not know of a native way to do it in d3. But you can easily modify the d3 selector API to skip animations by augmenting the d3 prototypes:

    HTML code to be animated:

    
        
    
    

    Animation and D3-augmentation code:

    function animate(color){
        d3.selectAll("rect")
        .attr("width", 0).attr("fill", "white")
        .transition().duration(1000)
        .attr("width", 100).attr("fill", color)
    }
    
    function augment(){
        // add a duration function to the selection prototype
        d3.selection.prototype.duration   = function(){ return this }
        // hack the transition function of d3's select API
        d3.selection.prototype.transition = function(){ return this }
    }
    
    animate("red")
    console.log("normal animation done")
    setTimeout( function(){
            augment()
            console.log("d3 hacked!")
            animate("green")
            console.log("animation skipped")
    }, 1200 )
    

    Attention! This hack may not work as a complete solution for you. You may want to extend this solution with other transition().* functions that are not available on the d3.selection.prototype and that you use in your application. You may also consider other forms of animation supported by d3. Maybe there is more than .transition() that I am not aware of.

提交回复
热议问题