故事开始
午饭时间,暗恋已久的学妹拉着我的衣袖:“学长学长,你能不能让这些爱心变成五颜六色的吗~”。
我在旁边笑开了花~~~
诶呀,口水流出来了。
我想最终效果是这样的(猜猜多少个爱心):
然后开始动手吧~
学啥本领
本文将带大家学习两个好东西:
1.生成随机色的方法;
2.Element.animate() 方法。
当然,还有撩妹技巧了~
代码走起
1. 画个小爱心
爱心怎么画,不是咱们本文重点,so,SVG搞起:
1 | <div id="heart"> |
2. 画一大堆爱心
现在删除到之前的 SVG 标签,换成动态生成咯~~
1 | let heartList = ''; |
一大堆小爱心出现啦:
3. 打造魔法棒
接下来我们要打造一把魔法棒,能让我们这些小爱心变成各种各样的颜色。
没错,这把魔法棒,就是用来生成随机颜色。
方法很多,我搜集以下几种简单好用的生成随机颜色的方法,基本我们业务随便一个都能用:
1 | function getRandomColor(){ |
随机色真好玩~
4. 五颜六色!变~
最后,我们修改前面 SVG 的代码片段,加入 getRandomColor
方法的调用:
1 | for(let i = 0; i <= n; i++){ |
5. 动起来吧!
这时候,每个爱心都静静躺着页面,是时候让它们动起来啦,为了学妹~
继续改造前面 SVG 代码,为每个 SVG 标签添加连续 ID 值:
1 | for(let i = 0; i <= n; i++){ |
生命随机放大倍数,并设置动画效果:
1 | let getRandomNum = () => Math.floor(Math.random()*2+1); |
6. 飞起来吧~
接下来,要让这些小爱心飞起来~
下面贴代码。
1 | html,body{ |
逻辑修改:
1 | let heartList = ''; |
聪明的你,再配上BGM,浪漫~
还能做更多有意思的小玩意,靠各位发挥啦。
故事结束
继续~
对了,送给学妹的代码我放在仓库:
https://github.com/pingan8787/Leo-JavaScript/blob/master/Leo-Demo/7-WeiteHeartPop.html