每隔几毫秒在给定的x-y坐标上显示元素

Show Element on given x-y coordinate every few ms

本文关键字:x-y 坐标 元素 显示 几毫      更新时间:2023-09-26

我有一个函数,从我的SignalR集线器中的另一个客户端接收xy坐标。每当clientA移动他的鼠标时,他的xy-coordinate被发送到ClientB

我正试图在clientB的屏幕上以该x-y坐标打印一个简单的@。这是有效的,但唯一的问题是它非常慢(我认为这是因为每次鼠标移动1px时都会调用该函数)。当我在clientA上移动鼠标几秒钟时,clientB屏幕上打印的"@"就落后了。

这与我为显示这个@而写的代码有什么关系吗?

hub.client.MouseMoved = function (x, y, id) {
        id = "@"; //for testing purposes
        var e = document.getElementById(id);
        
        if (!e) { //if e is not found, create e
            e = $('<div id="' + id + '">' + id + '</div>');
            e.css('position', 'absolute');
            console.dir(e);
            $(e).appendTo(document.body);
        }
        else {
            e = $(e);
        }
            e.css({ left: x + "px", top: y + "px" }); //set position of cursor to x y coordinate.
        }
    }

为了防止低性能,您可以使用计时器:

var timer;
function executeMouseMoved(x, y, id){
    id = "@"; //for testing purposes
    var e = document.getElementById(id);
        
    if (!e) { //if e is not found, create e
        e = $('<div id="' + id + '">' + id + '</div>');
        e.css('position', 'absolute');
        console.dir(e);
        $(e).appendTo(document.body);
    }
    else {
        e = $(e);
    }
    e.css({ left: x + "px", top: y + "px" }); //set position of cursor to x y coordinate.
}
hub.client.MouseMoved = function (x, y, id) {
    clearInterval(timer);
    timer = setTimeout(function(){executeMouseMoved(x,y,id);}, 50); //50ms
}

希望能有所帮助。

Js出价