d3.js v5入门之——实现运动缓动动画

Source

原文链接 https://blog.csdn.net/harmsworth2016/article/details/79776114

动画源码

<!--
@author Semper_Fi
-->
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <script src="https://d3js.org/d3.v5.min.js"></script>
    <title></title>
    <style>
    </style>
</head>

<body>
    
</body>
<script>
    var height = 3400
    var width = '100%'
    // 网页可见区域宽
    var bodyW = document.documentElement.clientWidth
    // 小球运动时间(毫秒)
    var duration = 2000
    // 运动缓动动画方式
    var animations = ['easeLinear', 'easePolyIn', 'easePolyOut', 'easePolyInOut', 'easeQuad', 'easeQuadIn', 'easeQuadOut',
    'easeQuadInOut', 'easeCubic', 'easeCubicIn', 'easeCubicOut', 'easeCubicInOut', 'easeSin', 'easeSinIn', 'easeSinOut', 'easeSinInOut',
    'easeExp', 'easeExpIn', 'easeExpOut', 'easeExpInOut', 'easeCircle', 'easeCircleIn', 'easeCircleOut', 'easeCircleInOut', 'easeElastic',
    'easeElasticIn', 'easeElasticOut', 'easeElasticInOut', 'easeBack', 'easeBackIn', 'easeBackOut', 'easeBackInOut',
    'easeBounce', 'easeBounceIn', 'easeBounceOut', 'easeBounceInOut']
    var svg = d3.select('body').append('svg').attr('height', height)
        .attr('width', width)
    var g = svg.append('g')
    // 标题文字
    var title = g.append('text')
    title.text('d3.js实现运动缓动动画').attr('fill', 'black')
        .attr('x', bodyW / 2)
        .attr('y', 20)
        .attr('text-anchor', 'middle')
        .style('font-size', '20px')
        .style('font-weight', 'bold')
        .attr('dy', 8)
    // 各种运动动画的小球
    animations.forEach((v, i) => {
        var g = svg.append('g')
        g.append('text').text((i + 1) + '.' + v).attr('fill', 'black')
        .attr('x', 100)
        .attr('y', 90 * (i + 1))
        .attr('text-anchor', 'middle')
        .style('font-size', '14px')
        .style('font-weight', 'bold')
        var circle = svg.append('circle').attr('cx', 100)
        .attr('cy', 90 * (i + 1) + 40).attr('r', 25).style('fill', 'steelblue')
        .style('cursor', 'pointer')
        .on('click', function () {
            circle.transition() // 启动过渡效果
                .duration(duration)
                .attr('cx', 800)
                .ease(d3[v])
        })
    })
</script>
</html>

动画效果

在这里插入图片描述

发布了25 篇原创文章 · 获赞 1 · 访问量 1687