>  기사  >  웹 프론트엔드  >  JS+CSS는 유성우의 애니메이션 효과를 구현합니다(코드)

JS+CSS는 유성우의 애니메이션 효과를 구현합니다(코드)

不言
不言앞으로
2018-11-12 17:11:535344검색

이 기사의 내용은 유성우의 애니메이션 효과를 구현하기 위한 JS+CSS(코드)에 대한 내용입니다. 필요한 친구들이 참고할 수 있기를 바랍니다.

1, 렌더링

JS+CSS는 유성우의 애니메이션 효과를 구현합니다(코드)

2, 소스 코드

HTML

 
     
          div > 
          div > 
          div > 
          div > 
         div > 
        <div>  div > 
          div > 
     div > 
 body ><p><strong>CSS</strong></p>
<pre class="brush:php;toolbar:false">/*  -  -  -  -  -  - 重启 -  -  -  -  -  -  */
 
 * {
     保证金:0 ;
     填充:0 ;
 }
 
 html,
  body {
      width:100% ;
     最小宽度:1000px ;
     身高:100% ;
     最小高度:400px ;
     溢出:隐藏;
 }

 / * ------------画布------------ * / 
 .container {
      position:relative;
     身高:100% ;
 }
 / *遮罩层* /
 
 #mask {
      position:absolute;
     宽度:100% ;
     身高:100% ;
     background:rgba(0,0,0,.8);
     z-index:900 ;
 }
 / *天空背景* /
 
 #sky {
      width:100% ;
     身高:100% ;
     background:线性渐变(rgba(0,150,255,1),rgba(0,150,255,.8),rgba(0,150,255,.5));
 }
 / *月亮* /
 
 #moon {
      position:absolute;
     上:50px ;
     右:200px ;
     宽度:120px ;
     身高:120px ;
     背景:rgba(251,255,25,0.938);
     border-radius:50% ;
     box-shadow:0  0  20px  rgba(251,255,25,0.5);
     z-index:9999 ;
 }
 / *闪烁星星* /
 
 .blink {
      position:absolute;
     background:rgb(255,255,255);
     border-radius:50% ;
     box-shadow:0  0  5px  rgb(255,255,255);
     不透明度:0 ;
     z-index:10000 ;
 }
 / *流星* /
 
 .star {
      position:absolute;
     不透明度:0 ;
     z-index:10000 ;
 }
 
 .star :: after {
      content:“” ;
     显示:块;
     边界:坚固;
     border-width:2px  0  2px  80px ;
     / *流星随长度逐渐缩小* / 
     border-color:透明透明透明rgba(255,255,255,1);
     border-radius:2px  0  0  2px ;
     transform:rotate(-45deg);
     transform-origin:0  0  0 ;
     盒子阴影:0  0  20px  rgba(255,255,255,.3);
 }
 / *云* /
 
 .cloud {
      position:absolute;
     宽度:100% ;
     身高:100px ;
 }
 
 .cloud-1 {
      bottom: - 100px ;
     z-index:1000 ;
     不透明度:1 ;
     变换:规模(1.5);
     -webkit-transform:scale(1.5);
     -moz-transform:scale(1.5);
     -ms-transform:scale(1.5);
     -o-transform:scale(1.5);
 }
 
 .cloud-2 {
      left: - 100px ;
     底部: - 50px ;
     z-index:999 ;
     不透明度:。5 ;
     变换:旋转(7deg);
     -webkit-transform:rotate(7deg);
     -moz-transform:rotate(7deg);
     -ms-transform:rotate(7deg);
     -o-transform:rotate(7deg);
 }
 
 .cloud-3 {
      left:120px ;
     底部: - 50px ;
     z-index:999 ;
     不透明度:。1 ;
     transform:rotate(-10deg);
     -webkit-transform:rotate(-10deg);
     -moz-transform:rotate(-10deg);
     -ms-transform:rotate(-10deg);
     -o-transform:rotate(-10deg);
 }
 
 .circle {
      position:absolute;
     border-radius:50% ;
     背景:#fff ;
 }
 
 .circle-1 {
      width:100px ;
     身高:100px ;
     上: - 50px ;
     左:10px ;
 }
 
 .circle-2 {
      width:150px ;
     身高:150px ;
     上: - 50px ;
     左:30px ;
 }
 
 .circle-3 {
      width:300px ;
     身高:300px ;
     上: - 100px ;
     左:80px ;
 }
 
 .circle-4 {
      width:200px ;
     身高:200px ;
     上: - 60px ;
     左:300px ;
 }
 
 .circle-5 {
      width:80px ;
     身高:80px ;
     上: - 30px ;
     左:450px ;
 }
 
 .circle-6 {
      width:200px ;
     身高:200px ;
     上: - 50px ;
     左:500px ;
 }
 
 .circle-7 {
      width:100px ;
     身高:100px ;
     上: - 10px ;
     左:650px ;
 }
 
 .circle-8 {
      width:50px ;
     身高:50px ;
     上:30px ;
     左:730px ;
 }
 
 .circle-9 {
      width:100px ;
     身高:100px ;
     上:30px ;
     左:750px ;
 }
 
 .circle-10 {
      width:150px ;
     身高:150px ;
     上:10px ;
     左:800px ;
 }
 
 .circle-11 {
      width:150px ;
     身高:150px ;
     上: - 30px ;
     左:850px ;
 }
 
 .circle-12 {
      width:250px ;
     身高:250px ;
     上: - 50px ;
     左:900px ;
 }
 
 .circle-13 {
      width:200px ;
     身高:200px ;
     上: - 40px ;
     左:1000px ;
 }
 
 .circle-14 {
      width:300px ;
     身高:300px ;
     上: - 70px ;
     左:1100px ;
 }

JS

//流星动画 
setInterval(function() {
     const obj = addChild(“#sky”,“p”,2,“star”);

    for(let i = 0 ; i <obj.children.length> {
                        obj.parent.removeChild(obj.children [I]);
                    }
                })
            }
        });
    }

},1000);

//闪烁星星动画 
setInterval(function() {
     const obj = addChild(“#stars”,“p”,2,“blink”);

    for(let i = 0 ; i <obj.children.length requestanimation const for let><p><strong>포장방법</strong></p>
<pre class="brush:php;toolbar:false">// -------------------------------------------动画---- ----------------------------------------------- 
//运动动画,调用Tween.js 
// ele:dom | 班级| id | 标签节点| 类名| id名| 标签名,只支持选择一个节点,类类名以及标签名只能选择页面中第一个
// attr:属性属性名
//值:目标值目标值
//时间:持续时间持续时间
//补间:定时function函数方程
// flag:Boolean判断是按值移动还是按位置移动,默认按位置移动
// fn:callback回调函数
//增加返回值:将内部参数对象返回,可以通过设置返回对象的属性stop为true打断动画
函数 requestAnimation(obj) {
     // -------------------------------------参数设置--------------------------------------------- 
    //默认属性
    const参数= {
         ele:null,
         attr:null,
         value:null,
         time:1000,
         tween:“linear”,
         flag:true,
         stop:false,
         fn:“”
    }

    //合并传入属性
    Object .assign(parameter,obj); //覆盖重名属性

    // -------------------------------------动画设置--------- ------------------------------------ 
    //创建运动方程初始参数,方便复用
    let start = 0 ; //用于保存初始时间戳
    let target =(typeof parameter.ele === “string”?document .querySelector(parameter.ele):parameter.ele),//目标节点 
        attr = parameter.attr,//目标属性 
        beginAttr = parseFloat(getComputedStyle(target)[attr]),// attr起始值 
        value = parameter.value,//运动目标值 
        count = value  -  beginAttr,//实际运动值 
        time = parameter.time,//运动持续时间,
        tween = parameter.tween,//运动函数
        flag = parameter.flag,
        callback = parameter.fn,//回调函数 
        curVal = 0 ; //运动当前值

    //判断传入函数是否为数组,多段运动 
    (function() {
         if(attr instanceof  Array){
            beginAttr = [];
            count = [];
            对于(让我的 ATTR){
                 常量 VAL = parseFloat(的getComputedStyle(目标)[I]);
                beginAttr.push(VAL);
                count.push(value  -  val);
            }
        }
        if(value instanceof  Array){
             for(let i in value){
                count [i] = value [i]  -  beginAttr [i];
            }
        }
    })();

    //运动函数
    功能 动画(时间戳) {
         如果(parameter.stop)返回 ; //打断
        //存储初始时间戳
        if(!start)start = timestamp;
        //已运动时间
        让 t =时间戳 - 开始;
        //判断多段运动
        if(beginAttr instanceof  Array){
             // const len = beginAttr.length //存数组长度,复用

            //多段运动第1类 - 多属性,同目标,同时间/不同时间
            if(typeof count === “number”){ //同目标
                //同时间
                if(typeof time === “number”){
                     if(t> time)t = time; //判断是否超出目标值

                    //循环attr,分别赋值
                    为(let i in beginAttr){
                         if(flag)curVal = Tween [tween](t,beginAttr [i],count,time); //调用Tween,返回当前属性值,此时计算方法为移动到
                        写入位置else curVal = Tween [tween](t,beginAttr [i],count + beginAttr [i],time); //调用Tween,返回当前属性值,此时计算方法为移动了
                        写入距离if(attr [i] === “opacity”)target.style [attr [i]] = curVal; //给属性赋值
                        else target.style [attr [i]] = curVal + “px” ; //给属性赋值

                        if(t <time> time [i])t = time [i]; //判断是否超出目标值

                        if(flag || attr [i] === “opacity”)curVal = Tween [tween](t,beginAttr [i],count,i); //调用Tween,返回当前属性值,此时计算方法为移动到
                        写入位置else curVal = Tween [tween](t,beginAttr [i],count + beginAttr [i],i); //调用Tween,返回当前属性值,此时计算方法为移动了
                        写入距离if(attr [i] === “opacity”)target.style [attr [i]] = curVal; //给属性赋值
                        else target.style [attr [i]] = curVal + “px” ; //给属性赋值
                    }

                    if(t  time)t = time; //判断是否超出目标值

                    for(let i in beginAttr){ //循环attr,count,分别赋值
                        //错误判断
                        if(!count [i] && count [i]!== 0){
                             throw  new  Error(
                                 “输入值的长度不是等于属性的长度“);
                        }

                        if(flag || attr [i] === “opacity”)curVal = Tween [tween](t,beginAttr [i],count [i],time); //调用Tween,返回当前属性值,此时计算方法为移动到
                        写入位置else curVal = Tween [tween](t,beginAttr [i],count [i] + beginAttr [i],time); //调用Tween,返回当前属性值,此时计算方法为移动了
                        写入距离if(attr [i] === “opacity”)target.style [attr [i]] = curVal; //给属性赋值
                        else target.style [attr [i]] = curVal + “px” ; //给属性赋值
                    }

                    if(t <time> time [i])t = time [i]; //判断是否超出目标值

                        //错误判断
                        if(!count [i] && count [i]!== 0){
                             throw  new  Error(
                                 “输入值的长度不等于属性的长度”);
                        }

                        if(flag || attr [i] === “opacity”)curVal = Tween [tween](t,beginAttr [i],count [i],time [i]); //调用Tween,返回当前属性值,此时计算方法为移动到
                        写入位置其他 curVal = Tween [tween](t,beginAttr [i],count [i] + beginAttr [i],time [i]) ; //调用Tween,返回当前属性值,此时计算方法为移动了
                        写入距离if(attr [i] === “opacity”)target.style [attr [i]] = curVal;
                        否则 target.style [attr [i]] = curVal + “px” ;
                    }

                    if(t  time)t = time;
        if(flag || attr === “opacity”)curVal = Tween [tween](t,beginAttr,count,time); //调用Tween,返回当前属性值,此时计算方法为移动到
        写入位置else curVal = Tween [tween](t,beginAttr [i],count + beginAttr,time); //调用Tween,返回当前属性值,此时计算方法为移动了
        写入距离if(attr === “opacity”)target.style [attr] = curVal;
        否则 target.style [attr] = curVal + “px” ;

        if(t <time><p><strong>3, 사례 분석</strong></p>
<p><strong>HTML</strong></p>
<p>노드가 많고, 최대한 현실적이고 재미있게 만들고 싶어서 노드에 임의의 위치도 추가했습니다. 따라서 노드의 출력은 JS에 의해 제어됩니다. HTML 측에서는 몇 개의 상위 요소 상자와 해당 ID 이름 및 클래스 이름만 작성되며 구조는 비교적 간단합니다. </p>
<p><strong>CSS</strong></p>
<p>CSS 부분에서 어려운 부분은 유성 스타일과 원으로 구름을 그린 후 구름을 쌓아 입체감을 주는 스타일입니다. </p>
<p>먼저 유성의 스타일에 대해 이야기해 보겠습니다. </p>
<pre class="brush:php;toolbar:false">#sky  .star {
      position:absolute;
     不透明度:0 ;
     z-index:10000 ;
 }
 
 .star :: after {
      content:“” ;
     显示:块;
     边界:坚固;
     border-width:2px  0  2px  80px ;
     / *流星随长度逐渐缩小* / 
     border-color:透明透明透明rgba(255,255,255,1);
     border-radius:2px  0  0  2px ;
     transform:rotate(-45deg);
     transform-origin:0  0  0 ;
     盒子阴影:0  0  20px  rgba(255,255,255,.3);
 }

먼저 공개 스타일을 추출하고 위치 지정 속성을 추가합니다.

그런 다음 별 뒤에 포스트 의사 클래스를 통해 유성을 추가하고 테두리 속성으로 그립니다.

1) 모델 도면: border-width 네 변의 순서는 위쪽, 오른쪽, 아래쪽, 왼쪽입니다. 마찬가지로 border-color의 순서도 위쪽, 오른쪽, 아래쪽, 왼쪽의 네 변입니다. 이렇게 border-width와 border-color를 일대일로 대응시키면 2px가 유성의 너비, 80px가 유성의 길이, 0픽셀의 유성이 꼬리임을 알 수 있고, 따라서 a를 형성합니다. 머리 너비 2px, 꼬리 0px, 길이 80px의 유성 모델

2) 약간 현실적: 테두리 반경 기준? 유성의 머리 부분에 둥근 모서리를 추가하여 더욱 사실적으로 보이게 합니다. 마지막으로 회전타를 통해 비스듬히 회전하여 떨어지는 것처럼 보이게 합니다.

3) 반짝임 추가: 유성에 약간의 후광을 추가합니다. 박스섀도우를 반짝반짝하게 만들어 보세요

위의 3단계를 거치면 별똥별이 완성됩니다.

그 다음은 구름 그림입니다.

구름의 코드가 비교적 길기 때문에 여기에는 올리지 않겠습니다. 방법은 하나씩 겹쳐서 덮어서 구름 모양을 완성하는 것 뿐입니다. .
구름 레이어를 완성한 후 하나를 복사한 다음 회전, 불투명도, 왼쪽 위치 지정 등을 사용하여 여러 구름 레이어가 희미해지고 겹치는 3차원 효과를 만듭니다.

JS

JS 부분에서는 유성을 다음과 같이 사용합니다. 예

setInterval(function() {
     const obj = addChild(“#sky”,“p”,2,“star”); //插入流星

    for(let i = 0 ; i <obj.children.length> {
                        obj.parent.removeChild(obj.children [I]); //动画结束删除节点
                    }
                })
            }
        });
    }

},1000);</obj.children.length>

여기서는 제가 직접 캡슐화한 두 가지 메서드를 사용했습니다. 하나는 requestAnimationFrame을 기반으로 하는 requestAnimation이고, 다른 하나는 appendChild를 기반으로 하는 addChild입니다.

임의의 별 위치 효과를 얻기 위해 타이머의 setInterval을 통해 유성은 지속적으로 삽입 및 삭제됩니다.

먼저 페이지에 매번 2개의 유성을 추가하지만 타이머의 간격 시간은 유성의 애니메이션 시간이므로 페이지의 유성 개수는 고정된 값이 아니지만 확실히 2보다 크다는 것이 보장됩니다. 그렇지 않으면 한 번에 2개의 유성이 약간 버려지게 됩니다.

그런 다음 루프를 통해(표현으로도 사용할 수 있으며 대체할 수 있습니다. -의 경우 가장 간단합니다) 새로 추가된 유성을 각각에 제공합니다. 페이지 내 임의 위치(위, 왼쪽), 임의 크기(크기), 임의 애니메이션 실행 시간(타이머)

마지막으로 사용된 루프에서 페이지에 새로 추가된 각 유성에 애니메이션을 적용하고 콜백을 전달합니다. 애니메이션 실행 후 노드. 여기서 주목해야 할 점은 애니메이션이 두 단계(나타남과 사라짐, 주로 불투명도 조절)로 나누어진다는 점이다. 게다가 여기서 처리할 때 각 유성은 300px 같은 거리로 이동합니다. 이 거리도 임의의 숫자로 제어할 수 있다고 생각하는데 게을러서 그렇게 하지 않았습니다.

4. 작은 문제

현재 두 가지 문제를 발견했습니다.

첫째, 페이지가 계속해서 노드를 추가하고 삭제하여 논스톱을 유발합니다. 리플로우 및 다시 그리기는 성능 집약적입니다.

두 번째 문제는 타이머가 지속적으로 노드를 추가하기 때문에 requestAnimationFrame 자체이며, requestAnimationFrame의 특성은 다른 페이지를 탐색하기 위해 현재 페이지를 떠날 때 애니메이션이 일시 중지된다는 것입니다. 이로 인해 문제가 발생합니다. 노드가 계속 추가되지만 애니메이션이 중지되고 실행되지 않습니다. 그러면 다음에 이 페이지로 돌아오면 애니메이션이 폭발하고 화면이 정지되는 것을 볼 수 있습니다. 어머니를 찾기 위해 함께 출발합니다.

5. 결론

이 작은 사례는 난이도 측면에서는 매우 간단하지만 사랑 표현, 사랑 보내기, 낭만적인 관계 등 확장성이 뛰어나며 순수 CSS로도 구현할 수 있습니다.

위 내용은 JS+CSS는 유성우의 애니메이션 효과를 구현합니다(코드)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 segmentfault.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제
이전 기사:브라우저 이벤트 루프에 대한 심층적인 살펴보기(코드 예제)다음 기사:브라우저 이벤트 루프에 대한 심층적인 살펴보기(코드 예제)

관련 기사

더보기