我正在参加「初夏创意投稿大赛」详情请看:初夏创意投稿大赛
前言
之前我在网上看到一个外国博主做了一个找到牛的游戏,就是通过鼠标移动,越靠近牛,牛的声音越大,来把隐藏的牛找出来。我也做了一个找到蝉,来给大家找到夏天的快乐。
代码
具体可点击下面代码块运行体验^_^
正文
首先我们把蝉放进来,网上找个图片,然后再在网上找个蝉的叫声,用audio
标签播放。代码如下:
<div class="box">
<div class="chan">
<img src="https://img2.baidu.com/it/u=1798386523,1764358553&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=600" alt="">
</div>
</div>
<audio id="audio" loop style="display: none;" controls src="https://img-qn.51miz.com/preview/sound/00/24/54/51miz-S245477-F2F52C9A-thumb.mp3"></audio>
<div class="btn">开始游戏</div>
<div class="success">被你找到啦</div>
然后给他们加点样式,把蝉隐藏起来。代码如下:
body{
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.box{
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
width: 100%;
height: 100%;
background-color: aquamarine;
}
.box:hover{
cursor: pointer;
}
.chan{
opacity: 0;
width: 50px;
height: 60px;
border-radius: 50%;
overflow: hidden;
position: absolute;
}
.chan img{
width: 100%;
height: 100%;
}
.btn{
position: absolute;
left: calc(50% - 50px);
top: 50px;
width: 100px;
height: 40px;
background-color: #fff;
border: none;
border-radius: 5px;
line-height: 40px;
color: darkslateblue;
text-align: center;
transition: all .2s linear;
}
.btn:hover{
cursor: pointer;
transform: scale(1.2);
}
接着我们使用【开始游戏】按钮触发,把蝉随机出现在屏幕的某一个地方,并播放蝉的叫声,声音先调小一点,代码如下:
let audio = document.getElementById("audio");
$(".btn").click(function () {
let left = Math.floor(Math.random() * 100) + "%";
let top = Math.floor(Math.random() * 100) + "%";
$(".chan").css("left", left).css("top", top);
audio.volume = 0.1;
audio.play();
$(".btn").css("display", "none");
})
后面我们通过监听鼠标的移动,拿到坐标,跟当前蝉的位置进行对比,然后根据相差的数值来跟音量比,相差数值越低,音量越大。因为音量只能是[0-1],所以我们使用 1/相差值 * 100,乘以100是让数值不那么低,且在可控范围。代码如下:
$(".box").on("mousemove", function (e) {
let left = Math.floor(+$(".chan").css("left").split("px")[0]) + 25;
let top = Math.floor(+$(".chan").css("top").split("px")[0]) + 30;
let leftCha = Math.abs(e.pageX - left);
let topCha = Math.abs(e.pageY - top);
if (leftCha > topCha) {
audio.volume = 1 / leftCha * 100 > 1 ? 1 : 1 / leftCha * 100;
} else {
audio.volume = 1 / topCha * 100 > 1 ? 1 : 1 / topCha * 100;
}
});
最后我们通过点击,判断当前坐标是否在蝉的里面,来找到隐藏的蝉,并显示出来,代码如下:
$(".box").on("click", function (e) {
console.log(e.pageX, e.pageY)
let left = Math.floor(+$(".chan").css("left").split("px")[0]) + 25;
let top = Math.floor(+$(".chan").css("top").split("px")[0]) + 30;
let leftCha = Math.abs(e.pageX - left);
let topCha = Math.abs(e.pageY - top);
if (leftCha <= 50 && topCha <= 60) {
audio.pause();
$(".chan").css("opacity", "1").css("width", "200px").css("height","auto").animate({
"left": "43%",
"top": "15%"
}, 1000);
$(".success").show(300)
}
});
至此,我们的功能就都完成了。