写一个判断鼠标进入方向切换图片的效果

直接看代码:

复制代码
<template>
    <div class="mainrouter centerWindi">
        <div ref="mouse" class="mouse" @mouseenter="handleMouse"></div>
    </div>
</template>
<script setup>
import { onMounted, ref } from 'vue';
import gsap from 'gsap'

const mouse = ref(null)
// 拿到鼠标的进入事件
// 监听鼠标进入事件
const handleMouse = (e) => {
    const theta = Math.atan2(mouse.value.offsetHeight, mouse.value.offsetWidth)
    const angle = Math.atan2(e.offsetX - mouse.value.offsetWidth / 2, mouse.value.offsetHeight / 2 - e.offsetY)
    const direction = ref('')
    console.log(theta, angle);
    if (angle < theta && angle > -theta) {
        direction.value = 'top';
        gsap.fromTo(mouse.value, {
            backgroundPositionY: `-${window.innerHeight}px`
        }, {
            backgroundPositionY: `0px`,
            duration: 0.5,
            ease: "none",//匀速
            // repeat:-1,//无限循环
            // yoyo: true,//往返运动
        })
    } else if (angle >= theta && angle < Math.PI - theta) {
        direction.value = "right";
        gsap.fromTo(mouse.value, {
            backgroundPositionX: `${window.innerHeight}px`
        }, {
            backgroundPositionX: `0px`,
            duration: 0.5,
            ease: "none",//匀速
            // repeat:-1,//无限循环
            // yoyo: true,//往返运动
        })
    } else if (angle >= Math.PI - theta || angle < -Math.PI + theta) {
        direction.value = "bottom";
        gsap.fromTo(mouse.value, {
            backgroundPositionY: `${window.innerHeight}px`
        }, {
            backgroundPositionY: `0px`,
            duration: 0.5,
            ease: "none",//匀速
            // repeat:-1,//无限循环
            // yoyo: true,//往返运动
        })
    } else {
        direction.value = "left";
        gsap.fromTo(mouse.value, {
            backgroundPositionX: `-${window.innerHeight}px`
        }, {
            backgroundPositionX: `0px`,
            duration: 0.5,
            ease: "none",//匀速
            // repeat:-1,//无限循环
            // yoyo: true,//往返运动
        })
    }

}



</script>

<style>
.mouse {
    border: 0.5px solid #000;
    background-color: red;
    width: 300px;
    height: 300px;
    background: url("./img/1.png") no-repeat;
    background-size: cover;
}
/* 路由 */
.mainrouter {
    background-color: white;
    width: 100%;
    height: 100%;
    border-radius: 4px;
    padding: 25px;
}
/* 居中 */
.centerWindi {
    @apply flex justify-center items-center;
}

</style>
相关推荐
FogLetter10 分钟前
从原生JS事件到React事件机制:深入理解前端事件处理
前端·javascript·react.js
轻语呢喃12 分钟前
js事件机制:监听、捕获、冒泡与委托
javascript
小公主22 分钟前
如何利用闭包封装私有变量?掌握防抖、节流与 this 问题的巧妙解决方案
前端
烛阴26 分钟前
JavaScript 的动态魔法:使用 constructor 动态创建函数
前端·javascript
前端 贾公子37 分钟前
tailwind ( uni ) === 自定义主题
前端
独立开阀者_FwtCoder44 分钟前
大制作!在线 CSS 动效 编辑神器!太炫酷了!
前端·javascript·github
白白李媛媛1 小时前
vue3中实现echarts打印功能
前端·vue.js·echarts
一只卡比兽1 小时前
全栈Node.js开发:集成第三方AI提供商Token的完整指南
javascript
尘心cx1 小时前
前端-HTML-day2
前端·html
歘chua1 小时前
组件封装:封装一个可复用的crud界面的思路
前端