童年回忆——家乡的月亮

808 阅读2分钟

mountains-ga2ef6e09a_1920.jpg

我正在参加「码上掘金挑战赛」详情请看:码上掘金挑战赛来了!

前言

中秋节,是阖家团圆的欢聚时刻。但是由于疫情频发,我所处的城市正处于管控中,中秋只能在小小的出租房里居家隔离。

突然就很想看看家乡的月亮,是否如小时候那般圆、那般亮,让人感觉温暖。城市的夜晚不常有月亮,偶尔瞥见的月亮在城市灯火的映照中,让人感觉孤寂。

今天简单实现一个大山中的圆月,以慰思乡之情。

实现思路

  1. 首先用css画一个背景,作为夜晚的天空,再给背景加上黑色的蒙层,增加黑夜的效果
.content {
  background: linear-gradient(to bottom, #333467 0%, #256fa1 87%);
  position: relative;
  overflow: hidden;
}
.content::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, .1);
  animation: light 20s linear;
  z-index: 11;
}
  1. 使用js动态生成星星,随机定位在天空中,并使用动画属性实现星星一闪一闪的效果。因为需要控制星星展示在页面的顶部,所以定位了一个固定高度的元素在页面顶部,并根据该元素的宽、高,获取星星的位置。
const sky = document.querySelector('.sky');
const leftDistance = sky.clientWidth - 4;
const topDistance = sky.clientHeight - 4;

//随机生成星星
let starNumber = 30;
function creatStar() {
  for (var i = 0; i < starNumber; i++) {
    let star = document.createElement('span');
    sky.appendChild(star);
    star.style.left = Math.random() * leftDistance + 'px';
    star.style.top = Math.random() * topDistance + 'px';
    star.style.animationDelay = Math.random() * 7 + 's';//添加动画延迟时间
  }
}
creatStar();
  1. 通过transformrotate属性和skewY属性,旋转元素和改变元素的形状;border-radius改变元素的边框弧度,实现山的简单形状。使用伪元素给大山增加黑色的蒙层,到时随着月亮的升起,黑色的蒙层慢慢变淡
.mountains {
  height: 100vh;
  overflow: hidden;
  position: relative;
  z-index: 90;
  transition: all 20s;
}
.mountain.one {
  position: absolute;
  left: -200px;
  bottom: -200px;
  width: 640px;
  height: 400px;
  background: #07203f;
  border-radius: 20%;
  transform: rotate(32deg) skewY(33deg);
  z-index: 98;
}
.mountain.two {
  position: absolute;
  left: -20px;
  bottom: -350px;
  width: 640px;
  height: 400px;
  background: #0a2447;
  border-radius: 20%;
  transform: rotate(32deg) skewY(33deg);
  z-index: 97;
}
.mountain.one::after,
.mountain.two::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-radius: 20%;
  animation: light 20s linear;
  background-color: rgba(0, 0, 0, .1);
}
  1. 画一个圆,并增加圆的阴影效果,实现一个简单的圆月,并使用动画属性让月亮从山的背后慢慢升起,一直到页面的顶部。月亮快要到页面的顶部时,使用js控制减少星星的数量。
.moon {
  position: absolute;
  background: white;
  border-radius: 50%;
  width: 120px;
  height: 120px;
  left: 20px;
  bottom: 0;
  transform: translate3d(50vw, -80vh, 0);
  animation: rise 30s linear;
  box-shadow: 0 0 20px 7px #fff;
  z-index: 77;
}
function disappearStar(){
  let reduceStar = document.querySelectorAll('.sky span');
  starNumber = 15;
  for (let i = 0; i < starNumber; i++) {
    sky.removeChild(reduceStar[i]);
  }
}
setTimeout(() => {
  disappearStar()
}, 25000)
  1. 在网上找了一张卡通人物(ps: 找张合适的太不容易了,还是aj帮忙找的,并且修了下图),放在页面底部,坐着静静地赏月
.person {
  position: fixed;
  bottom: -20px;
  right: 0;
  width: 50%;
  z-index: 10;
}
.person img{
  width: 100%;
}

展示效果

在码上掘金中发布了相关代码,具体的效果展示如下: code.juejin.cn/pen/7141368… 最后,祝大家中秋节快乐!