JS How to get the coordinates of the mouse in a label

Mouse coordinate system is too important. Use the mouse coordinates, you can do many things, such as the game follows the mouse, the page with a mouse position to do special effects, and so on.

Get mouse coordinates, two cases are discussed.

1. Only one label, no sub-label case

This is the simplest case, the use of the event object event offsetX and offsetY property to get the coordinates of the mouse in the label.

Q: Why use an event object?

A: Because often get mouse coordinates associated with mouse events.

for example:

<style>
        .box{
            width: 400px;
            height: 400px;
            background: #ccc;
            margin-left: auto;
            margin-right: auto;
        }
 </style>
<div class="box" id="box">
    这个是内容
</div>

<script>
    let box = document.getElementById("box");
    box.addEventListener("click",function(event){
        console.info( event.offsetX, event.offsetY );
    });
</script>

Mouse anywhere box, will output a corresponding coordinates in the control panel.

Well example, the drawing canvas may be a plate . Interested friends can try.

I of course a video, in this case said: https://v.huya.com/play/291503364.html

2. The case contains child tags

Use the event object event of offsetX, offsetY property, if there are sub-target tag, the resulting child is a relative coordinate labels.

This awkward ~

<style>
        .box{
            width: 400px;
            height: 400px;
            background: #ccc;
            margin-left: auto;
            margin-right: auto;
        }
        .small{
            width: 200px;
            background: #666666;
            height: 200px;
            margin-left: auto;
            margin-right: auto;
        }
</style>
<div class="box" id="box">
    <div class="small" id="small">

    </div>
</div>

<script>
    let box = document.getElementById("box");
    box.addEventListener("click",function(event){
        // 如果点在了子标签上,得到的是相对子标签的坐标。
        console.info( event.offsetX, event.offsetY );
    });
</script>

Solution:

In order to obtain the coordinates in the box, you may be utilized box.getBoundingClientRect () Gets the position in the window box. Using the coordinates of the mouse in the window, minus the coordinates of the box in the window on it.
Look at this getBoundingClientRect () is what.

<div class="box" id="box">
    <div class="small" id="small">

    </div>
</div>

<script>
    let box = document.getElementById("box");
    box.addEventListener("click",function(event){
        let sPos = box.getBoundingClientRect();
        console.info( sPos );
        console.info( sPos.x, sPos.y ); // 输出标签左上角在窗口的坐标。
    },true);
</script>

getBoundingClientRect, the literal meaning of: obtaining a rectangular area client (client, especially browser) is formed. It can get coordinates and boundary value tag in the browser window.

Coordinates of the mouse in the browser window is very simple event object event of clientX and clientY properties.

So get the mouse mode within the specified label is:

let box = document.getElementById("box");
box.addEventListener("click",function(event){
    let sPos = box.getBoundingClientRect();
    // 输出鼠标在标签中的坐标
     console.info( event.clientX-sPos.x, event.clientY-sPos.y ); 
},true);

3. The package as a function

 let getMousePostion = function(box,event){
        /*
        * 返回鼠标在某个标签里的坐标,数组
        * box: 某个标签对象
        * event: 事件对象
        * */
        let sPos = box.getBoundingClientRect();
        return  [ event.clientX-sPos.x, event.clientY-sPos.y ];
    };

Classic Case 1: Hold down the mouse push flip images

 Look Effect: In order to reduce the volume, thumbnail picture, picture quality is reduced.

Hold down the mouse to move the div # box can be controlled from the picture flipped.

Detailed code: do not explain, look at the comment.

 <style>
        .box{
            width: 800px;
            height: 600px;
            position: relative;
            margin-left: auto;
            margin-right: auto;
            background: #f2f2f2;
            perspective: 500px;
        }
        .img{
            width: 242px;
            height: 309px;
            overflow: hidden;
            position: absolute;
            left:50%;
            top:50%;
            margin-left: -121px;
            margin-top:-154.5px;
            transition:all 0.2s;
        }
 </style>

<div class="box" id="box">
    <div class="img" id="img">
        <img id="pic" src="../images/meinv.png" width="242" height="309" alt="">
    </div>
</div>

<script>
    // 找标签
    let box = document.getElementById("box"); // 标签范围
    let img = document.getElementById("img"); //  图片div
    let pic = document.getElementById("pic"); //  图片img
    // 极端情况,鼠标从 box 左边到右边的距离,就让图片翻转 180deg。
    let degreeNum = 180;
    // 开始的鼠标 x 位置。
    let startPos = 0;
    // 开始图片的翻转度。
    let startDeg = 0;
    // 鼠标移动控制的旋转度
    let xDeg = 0;
    // 获取鼠标坐标函数
    let getMousePostion = function(box,event){
        /*
        * 返回鼠标在某个标签里的坐标,数组
        * box: 某个标签的 id
        * event: 事件对象
        * */
        let sPos = box.getBoundingClientRect();
        return  [ event.clientX-sPos.x, event.clientY-sPos.y ];
    };
    // 鼠标移动事件处理
    let mouseMoveFun = function(event){
        let nowPos = getMousePostion(box,event)[0];
        let disX = nowPos - startPos ;
        // 鼠标控制的旋转度:鼠标移动距离 / box宽度 * 180
            xDeg = disX / box.offsetWidth * degreeNum;
        // 图片旋转:起始度+鼠标控制的旋转度
       img.style.transform = `rotateY(${startDeg+xDeg}deg)`;
    };

    // 鼠标按下事件:开始拖动
    box.addEventListener("mousedown",function(event){
        startPos = getMousePostion(box,event)[0]; // 按下那一瞬间的鼠标坐标
        box.addEventListener("mousemove",mouseMoveFun);
    });
    // 鼠标松开,取消鼠标移动事件,且重新设置图片旋转的起始度。
    box.addEventListener("mouseup",function(event){
        startDeg = startDeg+xDeg ;
        box.removeEventListener("mousemove",mouseMoveFun);
    });

    // 防止图片被鼠标拖拽
    pic.addEventListener("dragstart",function(event){
        event.preventDefault();
    });
</script>

Classic Case 2: sliding the mouse to control the tilt of the picture

Mouse div # box in the slide, the picture shows the corresponding inclination, do not need to hold down the mouse.

  <style>
        .box{
            width: 800px;
            height: 600px;
            position: relative;
            margin-left: auto;
            margin-right: auto;
            background: #f2f2f2;
            perspective: 500px;
        }
        .img{
            width: 242px;
            height: 309px;
            overflow: hidden;
            position: absolute;
            left:50%;
            top:50%;
            margin-left: -121px;
            margin-top:-154.5px;
            transition:all 0.2s;
        }

</style>

让图片在 -60deg 到 60deg 之间倾斜。
<div class="box" id="box">
    <div class="img" id="img">
        <img src="../images/meinv.png" width="242" height="309" alt="">
    </div>
</div>

<script>
    let box = document.getElementById("box");
    let img = document.getElementById("img");
    let boxCenter = [400,300];  //  box 中心点。
    let degreeNum = 60;  // 图片的倾斜度

    let getMousePostion = function(box,event){
        /*
        * 返回鼠标在某个标签里的坐标,数组
        * box: 某个标签的 id
        * event: 事件对象
        * */
        let sPos = box.getBoundingClientRect();
        return  [ event.clientX-sPos.x, event.clientY-sPos.y ];
    };
    box.addEventListener("mousemove",function(event){
        let mousePos = getMousePostion(box,event); // 获取鼠标在 box 里的坐标,数组。
        let disX = mousePos[0]-boxCenter[0];
        let disY = mousePos[1]-boxCenter[1];

        let xDeg = disX / boxCenter[0] * degreeNum;
        let yDeg = disY / boxCenter[1] * degreeNum;
        console.info( xDeg );
        img.style.transform = `rotateY(${xDeg}deg)  rotateX(${yDeg}deg)`;
    });
</script>

Classic Case 3: pseudo-3D's banner

Combination of the above knowledge, you can make banner of a pseudo-3D.

Principle: the use of the mouse position from the midpoint of the banner to control the displacement of individual elements (Translate) and tilt (rotateY).

HTML tags:

<div class="banner"   id="banner">
    <img class="ren"  id="ren" src="images/renwu.png" width="281" height="430" alt="">
    <div class="text" id="text">WHITE MOUSE</div>
    <img class="bg"   id="bg" src="images/bannerbg.jpg" alt="">
</div>

CSS: individual elements overlap, the relative positioning of the banner, banner inside each element absolute positioning.


    *{
        margin: 0;
        padding: 0;
    }
    .banner{
        width: 1200px;
        height: 430px;
        overflow: hidden;
        margin-left: auto;
        margin-right: auto;
        position: relative;
        transform-style: preserve-3d;  /* 3D 效果,写在容器上,把内部变成 3D 空间 */
        perspective: 500px;            /* 3D 透视,写在容器上 */
        background: #ccc;
    }
    .banner img{
        transition:all 0.2s;
    }
    .bg{
        transform: scale(1.1);
    }
    .ren{
        position: absolute;
        left:50%;
        top:50%;
        margin-left: -240px;
        margin-top: -214px;
        z-index: 2;
        transform: translateZ(50px);
    }
    .text{
        z-index: 1;
        width: 1200px;
        height: 200px;
        line-height: 150px;
        font-size: 150px;
        text-align: center;
        position: absolute;
        left:50%;
        top:50%;
        margin-left: -600px;
        margin-top: -100px;
        color: #fff;
        text-shadow: -10px 5px 0 rgba(0,0,0,0.5);
        transform: translateZ(20px);
    }
// 找标签
let banner = document.getElementById("banner");
let ren = document.getElementById("ren");
let text = document.getElementById("text");
let bg = document.getElementById("bg");
// 相关数据
let bannerCenter = [600,215];  // 中心点
let deg = 2;  // 元素最多倾斜 2 度。
let weizhi = [20,10,5]; // ren ,text ,bg。近中远,近点的内容移动距离大点。
// 获取鼠标坐标函数
let getMousePosition = function(box,event){
    let pos = box.getBoundingClientRect();
    return [ event.clientX - pos.x, event.clientY - pos.y ];
};

let moveFun = function(event){
    let mousePosX = getMousePosition(banner, event)[0];
    // 关键数据:鼠标跟中点的水平距离
    let disX = mousePosX - bannerCenter[0];
    // 关键数据:鼠标跟中点的水平距离 / banner宽度一半  。
    // 利用这个比例来计算各个元素的倾斜度和位移。
    let  weizhiBiLi= disX / bannerCenter[0];
    ren.style.transform = `translateZ(50px)  rotateY(${deg*weizhiBiLi}deg)    translateX(${weizhiBiLi*weizhi[0]}px)`;
    text.style.transform = `translateZ(20px) rotateY(${deg*weizhiBiLi}deg)    translateX(${weizhiBiLi*weizhi[1]}px)`;
    bg.style.transform   = `scale(1.1)       rotateY(${deg*weizhiBiLi}deg)    translateX(${weizhiBiLi*weizhi[2]}px)`;
};
// 添加监听事件
banner.addEventListener("mousemove",moveFun);

Figure material: 

I feel good point a praise chant ~

 

 

 

Published 86 original articles · won praise 146 · views 50000 +

Guess you like

Origin blog.csdn.net/weixin_42703239/article/details/105001088