两种background连续背景图动画

415 阅读1分钟

1. background-position的用法:

background-position关键字(top、bottom、left、right、center)

1.两个值:

background-position可以取两个值,一个为横轴方向,一个为纵轴方向。

1.比如你想要把背景图定位在右下角,只需这样写:

background-position: right bottom;

2.当然你也阔以把顺序反过来,丝毫没影响!

background-position: bottom right;

3.但是需要注意的是,仅仅在两个值都为关键字时才无关其顺序,因为根据关键字浏览器就能自动识别它是横轴方向还是纵轴方向。

下面这种写法是错误的

background-position: bottom 0;

2.单个值

background-position取单个值时,另一个值默认设为center。例如:

background-position: top;

相当于

background-position: top center;
/* 或者 */
background-position: center top;

2.背景图连续不间断移动:

20220915104949.gif

import React from 'react';
import styled, { keyframes } from '@zycfc/styled-px2vw';
import { useNavigate } from 'react-router-dom';
import entryBg from '../../assets/images/entry_bg.png';
import motobg from '../../assets/images/motorcycle.gif';
import btnbg from '../../assets/images/entry_btn.png';

const Home: React.FC = () => {
  const navigate = useNavigate();
  return (
    <Wrapper>
      <MotoBg />
      <BtnBg
        onClick={(): void => {
          navigate('/screen-page');
        }}
      />
    </Wrapper>
  );
};

export default Home;

const move = keyframes`
    0% {
        background-position: top 0 left 100vw
    }
    100% {
        background-position: top 0 right 0
    }
`;

const Wrapper = styled.div`
  width: 750px;
  min-height: 100vh;
  background: url(${entryBg}) repeat 0;
  background-size: auto 100%;
  position: relative;
  animation: ${move} 5s linear infinite;
`;

const MotoBg = styled.div`
  width: 507px;
  height: 304px;
  background: url(${motobg}) center center no-repeat;
  background-size: 507px 304px;
  position: absolute;
  bottom: 400px;
  left: 100px;
`;
const BtnBg = styled.div`
  width: 300px;
  height: 136px;
  background: url(${btnbg}) center center no-repeat;
  background-size: 300px 136px;
  position: absolute;
  bottom: 180px;
  left: 225px;
`;

3. 背景图移动最后停止:

20220915105142.gif

import React, { useEffect } from 'react';
import styled, { keyframes } from '@zycfc/styled-px2vw';
import entryBg from '../../assets/images/street.png';
import motobg from '../../assets/images/motorcycle.gif';

const Screenpage: React.FC = () => {
  return (
    <Wrapper>
      <MotoBg />
    </Wrapper>
  );
};

export default Screenpage;

const move = keyframes`
    0% {
        background-position:  0;
    }
    100% {
        background-position: 100%;
    }
`;

const Wrapper = styled.div`
  width: 750px;
  min-height: 100vh;
  background: url(${entryBg}) no-repeat;
  background-size: auto 100%;
  position: relative;
  overflow: hidden;
  animation: ${move} 5s linear forwards;
`;

const MotoBg = styled.div`
  width: 507px;
  height: 304px;
  background: url(${motobg}) no-repeat;
  background-size: 507px 304px;
  position: absolute;
  bottom: 400px;
  left: -100px;
`;