温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在html5中通过JSON实现动画效果

发布时间:2022-02-22 15:34:00 来源:亿速云 阅读:556 作者:iii 栏目:开发技术

本篇内容主要讲解“如何在html5中通过JSON实现动画效果”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“如何在html5中通过JSON实现动画效果”吧!

1.demo.html里面有很多内联的东西,使用时堆积在页面内不好看

仔细看一下,其实demo.html把js和json都放进去了,这时候我们可以把js和json单独分出来,js的话可以使用cdn上提供的地址

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.4.3/lottie.min.js">
</script>

动画需要的json数据放在data.json文件里面,但是给出的json文件里面的数据格式是这样的

那如果你要在单独的一个html里面使用script的方式引入json文件的话,会报错,所以需要修改json文件,在前面加上变量,赋值。

这样你可以通过像引入js文件的方式一样的引入该json:

<script type="text/javascript" src="./data.json"></script>

这样可用的demo.html就缩减成了下面这样:

<html xmlns="http://www.w3.org/1999/xhtml">
<meta charset="UTF-8">
<head>
    <style>
        body{
            background-color:black;
            margin: 0px;
            height: 100%;
            overflow: hidden;
        }
        #lottie{
            background-color:#fff;
            width:100%;
            height:100%;
            display:block;
            overflow: hidden;
            transform: translate3d(0,0,0);
            text-align: center;
            opacity: 1;
        }

    </style>
</head>
<body>


<div id="lottie"></div>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.4.3/lottie.min.js"></script>

<script type="text/javascript" src="./data.json"></script>

<script>
    var params = {
        container: document.getElementById('lottie'),
        renderer: 'svg',
        loop: true,
        autoplay: true,
        animationData: animationData
    };

    var anim;

    anim = lottie.loadAnimation(params);

</script>
</body>
</html>

当然,你如果使用的是js模块化编程的话,可以不用更改data.json,直接import进来就行了,如下:

import animationData from './data.json'

2.使动画适配移动端

之所以觉得这是个坑是因为,设计师给我的动画是全屏且非透明底的,然后她要求我将这个动画以宽度100% 高度垂直居中截取的方式定位,我在浏览器里面试了下,360*640屏幕下,宽度100%,表现形式是这样的(看上去是高度100% 宽度适配居中 两边漏出了黑色的背景色,见下图蓝色框起来的部分)

换成iPhone X的屏幕下,相反,表现出来是宽度100% 高度适配居中,上下漏出黑色背景色,见下图蓝色框起来的部分(究其原因是因为iphonex屏幕较长

这个布局好熟悉哇,跟img的object-fit属性取值为contain的时候表现一致(object-fit也是宝藏,有兴趣的同学可以去研究一下,非常好用)

我这里解决设计师的需求主要增加下面的代码:

js部分:
setTimeout(function() {
    document.getElementsByTagName('svg')[0].style.height = 'auto';
}, 50);
css部分:(给lottie增加flex布局)
#lottie {
    width:100%;
    height:100%;
    transform: translate3d(0,0,0);
    text-align: center;
    opacity: 1;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 3;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
}

到此,相信大家对“如何在html5中通过JSON实现动画效果”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI