分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 网页技术

如何利用 CSS 的动画原理,创作一个乒乓球对打动画

发布时间:2023-09-06 02:23责任编辑:白小东关键词:CSS动画


效果预览


在线演示

按下右侧的“点击预览”按钮可以在当前页面预览,点击链接可以全屏预览。


https://codepen.io/comehope/pen/rvgLzK


可交互视频教程


此视频是可以交互的,你可以随时暂停视频,编辑视频中的代码。


请用 chrome, safari, edge 打开观看。


https://scrimba.com/p/pEgDAM/cW7gZfb


源代码下载


本地下载

每日前端实战系列的全部源代码请从 github 下载:


https://github.com/comehope/front-end-daily-challenges


代码解读


定义 dom,容器中包含左拍、小球和右拍:

<div class="court"> ???<div class="left-paddle"></div> ???<div class="ball"></div> ???<div class="right-paddle"></div></div>

居中显示:

body { ???height: 100vh; ???display: flex; ???align-items: center; ???justify-content: center; ???background: linear-gradient(silver, dimgray);}

调整盒模型:

* { ???box-sizing: border-box;}

画出球案:

.court { ???width: 20em; ???height: 20em; ???color: white; ???border: 1em solid currentColor;}

画出左拍:

.court { ???position: relative;}.left-paddle ???width: 1em; ???height: calc(50% - 1em); ???background-color: currentColor; ???position: absolute; ???top: 1em; ???left: 1em;}

让左拍动起来:

.left-paddle { ???animation: left-moving 1s linear infinite alternate;}@keyframes left-moving { ???to { ???????transform: translateY(100%); ???}}

类似地,画出右拍:

.right-paddle ???width: 1em; ???height: calc(50% - 1em); ???background-color: currentColor; ???position: absolute; ???top: 1em; ???left: 1em; ???bottom: 1em; ???right: 1em;}

类似地,让右拍动起来:

.right-paddle { ???animation: right-moving 1s linear infinite alternate;}@keyframes right-moving { ???to { ???????transform: translateY(-100%); ???}}

画出小球:

.ball { ???width: 100%; ???height: 1em; ???border-left: 1em solid currentColor; ???position: absolute; ???left: 2em; ???top: calc(50% - 1.5em);}

让小球动起来:

.ball { ???animation: bounce 1s linear infinite alternate;}@keyframes bounce { ???to { ???????left: calc(100% - 3em); ???}}

最后,重构一下左右拍的代码,合并共有属性:

.left-paddle,.right-paddle { ???width: 1em; ???height: calc(50% - 1em); ???background-color: currentColor; ???position: absolute; ???animation: 1s linear infinite alternate;}.left-paddle { ???top: 1em; ???left: 1em; ???animation-name: left-moving;}.right-paddle { ???bottom: 1em; ???right: 1em; ???animation-name: right-moving;}

大功告成!

原文地址:https://segmentfault.com/a/1190000015002553

如何利用 CSS 的动画原理,创作一个乒乓球对打动画

原文地址:https://www.cnblogs.com/datiangou/p/9994345.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved