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

直接看代码:

复制代码
<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>
相关推荐
b1gbrother16 分钟前
让你的Claude Code变得更聪明
前端·程序员
国家不保护废物25 分钟前
多模态模型数据传输的秘密武器:html5对象Blob深度解析
前端·面试·html
用户25191624271125 分钟前
Canvas之概述,画布与画笔
前端·javascript·canvas
南方kenny25 分钟前
前端小知识:搞懂 BFC块级格式化上下文,告别面试“拦路虎”!
前端·css·面试
邵洛26 分钟前
前端导出excel表格并修改导出表格样式
前端
风舞26 分钟前
JavaScript 核心概念及代码示例的梳理
前端
学长学姐我该怎么办28 分钟前
从零开始学前端html篇2
前端·html
尘世中一位迷途小书童29 分钟前
从零实现 Canvas 图形拖拽:让你的网页动起来!
前端
mrsk30 分钟前
JavaScript之变量的解构赋值全面解析(●'◡'●)
前端·javascript·面试
归于尽30 分钟前
回调函数在Node.js中是怎么执行的?
前端·javascript·node.js