首页 > 解决方案 > How to track the position of the mouse on X-axis in JavaScript?

问题描述

I want to know how to track the position of the mouse on X-axis on the screen. Based on limited knowledge of Java/Processing, it is something similar to mouseX in Java. In addition, I want to rotate an image element based on the position of the mouse on X-axis. It would be nice to receive some pieces of advice.

标签: javascript

解决方案


一个流行的类似于 Processing 的库/框架是 P5.js(由同一个人开发,但用于 javascript),它可以为您处理这个

但在 vanilla javascript 中,你需要一个事件监听器

var mouse = {
    x: undefined, 
    y:undefined
};

window.addEventListener("mousemove", function(event) {
    mouse.x = event.x;
    mouse.y = event.y;
});

它的作用是监听鼠标移动,然后将其记录到对象

然后取mouseX位置你可以写

var mouseX = mouse.x;

或者你可以直接从

mouse.x;
//still the same

推荐阅读