检查鼠标是否在窗口内或窗口外

rta7y2nd  于 2021-09-13  发布在  Java
关注(0)|答案(0)|浏览(163)

我已经看到这类问题已经得到了回答,但是每个答案都有点模糊,或者有一些交叉兼容性问题,或者太超出了我的理解。那么有没有人可以给我一个最新的、完整的,清楚(显示并解释所有涉及的步骤)答案?我不想让鼠标在窗口外时圆圈变大。我没有使用jquery(在许多答案中都有)。我应该使用它吗?有没有办法用纯javascript实现这一点?感谢您的帮助,如果我的代码有点多余,请原谅:)

var canvas = document.querySelector("canvas");
var c = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var mouse = {
    x: undefined,
    y: undefined
}
window.addEventListener("mousemove", function(event){
    mouse.x = event.x;
    mouse.y = event.y;
})
window.addEventListener("resize", function(){
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
})

var colorArray = [
    "#6CC61D",
    "#E05132",
    "#278E83",
    "#A633D4"
]

function Circle(x,y,dx,dy,radius){
    this.x  = x;
    this.y = y;
    this.dx = dx;
    this.dy = dy;
    this.radius = radius;
    this.color = colorArray[Math.floor(Math.random() * colorArray.length)];

    this.draw = function(){
        c.beginPath();
        c.arc(this.x,this.y,this.radius,0,Math.PI*2,false);
        c.fillStyle = this.color;
        c.fill()
    }
    this.update = function(){
        if (this.x + this.radius>window.innerWidth  ||  this.x -this.radius<0){
            this.dx = - this.dx;}
        if (this.y + this.radius > window.innerHeight || this.y - this.radius < 0) {
            this.dy = - this.dy;
        }
        if (mouse.x - this.x < 50 && mouse.x - this.x > - 50 && mouse.y - this.y < 50 && mouse.y - this.y > - 50 && this.radius<50 ){
            this.radius += 1;
        }
        else if(this.radius>2){
            this.radius -= 1;
        }
        this.x += this.dx;
        this.y += this.dy;
        this.draw();

}
}
var circleArray = [];
for (var i = 0; i < 600; i++) {
    var x = Math.random() * (window.innerWidth - radius * 2) + radius;
    var y = Math.random() * (window.innerHeight - radius * 2) + radius;
    var dy = (Math.random() - 0.5) * 8;
    var dx = (Math.random() - 0.5) * 8;
    var radius = 30;

        circleArray.push(new Circle(x, y, dx, dy, radius));
    }

function animate(){
    requestAnimationFrame(animate);
    c.clearRect(0,0,window.innerWidth,window.innerHeight);
    for (var i = 0;i < circleArray.length;i++){
        circleArray[i].update()
    }
    circle.update();
}
animate();

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题