简体   繁体   English

跟随鼠标光标时的延迟<canvas>

[英]Latency when following mouse cursor on <canvas>

I'm trying to draw a rectangle (or other path) at the cursors position. 我正试图在光标位置绘制一个矩形(或其他路径)。

The issue is, if you move your mouse fast enough, the drawing lags behind the cursor considerably (chases it). 问题是,如果你足够快地移动鼠标,那么绘图会大大滞后于光标(追逐它)。

To reproduce/ test the issue, I've tried to produce code that is as lean as possible. 为了重现/测试问题,我尝试生成尽可能精简的代码。 However there's still a noticeable gap [between the cursor and the rectangle] due to rendering latency, even on a computer with decent specs (Chrome Beta 37, Fedora 20, i7 4770k, etc) 然而,由于渲染延迟,在光标和矩形之间仍然存在明显的差距,即使在具有不错规格的计算机上(Chrome Beta 37,Fedora 20,i7 4770k等)

Can anyone posit to the cause, or suggest improvements to the following code to reduce latency: 任何人都可以为这个原因做出贡献,或建议改进以下代码以减少延迟:

http://jsfiddle.net/AGp2w/4/ http://jsfiddle.net/AGp2w/4/

var canvas = document.getElementsByTagName('canvas')[0];
var canvasDim = {
    width: canvas.width,
    height: canvas.height
};
var canvasOffset = canvas.getBoundingClientRect();

var context = canvas.getContext('2d');
context.stroke = "#000000";
context.fill = "#000000";

var currentPosition = {x:0, y:0};
var previousPosition = currentPosition;
var onlyClearPreviousPositon = true;

canvas.onmousemove = function(e){
    currentPosition = {
        x: e.clientX - canvasOffset.left,
        y: e.clientY - canvasOffset.top
    };
};
function drawAtCursor(){
    if (onlyClearPreviousPositon){
        // experiment - try not clearing the whole canvas 
        context.clearRect(previousPosition.x - 4, previousPosition.y - 4, 8, 8);
        previousPosition = currentPosition;
    } else {
        context.clearRect(0, 0, canvasDim.width, canvasDim.height);
    }
    context.fillRect(currentPosition.x - 4, currentPosition.y - 4, 8, 8);
    window.requestAnimationFrame(drawAtCursor);   
}

drawAtCursor();

This has a tiny bit less latency, but is not useful in a real app: 这有一点点延迟,但在真正的应用程序中没用:

function handleMouseMove(e){
    ctx.clearRect(mouseX-1,mouseY-1,9,9);
    mouseX=e.clientX-offsetX;
    mouseY=e.clientY-offsetY;
    ctx.fillRect(mouseX,mouseY,8,8);
}

The mouse pointer will always be quicker than drawing, so your best bet is not to give the user's eye a reason to perceive latency: 鼠标指针总是比绘图更快,所以最好的选择不是让用户的眼睛有理由感知延迟:

Turn off the mouse cursor while the user is drawing. 在用户绘图时关闭鼠标光标。

http://jsfiddle.net/m1erickson/Cf5TX/ http://jsfiddle.net/m1erickson/Cf5TX/

The moving rectangle will act as the mouse cursor, but if the user needs a visual guide, you can: 移动的矩形将用作鼠标光标,但如果用户需要可视指南,您可以:

Also draw crosshairs using a couple of lines. 还使用几行绘制十字准线。

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

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