简体   繁体   English

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

[英]Show Element on given x-y coordinate every few ms

I have a function that, recieves xy coordinates from another client in my SignalR hub. 我有一个函数,从我的SignalR集线器中的另一个客户端SignalR xy坐标。 whenever clientA moves his mouse, his xy-coordinate is sent to ClientB . 每当clientA移动他的鼠标时,他的xy-coordinate就会被发送到ClientB

I am trying to print a simple @ in the screen of clientB at that xy coordinate. 我试图在xy坐标的clientB屏幕上打印一个简单的@ This works, but the only problem is that it is super slow (I think because the function gets called for every time the mouse moves 1px ). 这是有效的,但唯一的问题是它超级慢(我认为因为每次鼠标移动1px时都会调用该函数)。 When i move my mouse on clientA for a few seconds, the printed "@" on clientB 's screen is falling behind. 当我在clientA上移动鼠标几秒钟时, clientB屏幕上打印的“@” clientB落后。

Has this anything to do with the code i wrote to display this @ ? 这与我写的代码有什么关系来显示这个@

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.
        }
    }

To prevent low performance, you can use a timer : 为防止性能下降,您可以使用计时器:

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
}

Hope it helps. 希望能帮助到你。

JsFiddle 的jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM