簡體   English   中英

跟隨鼠標光標時的延遲<canvas>

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

我正試圖在光標位置繪制一個矩形(或其他路徑)。

問題是,如果你足夠快地移動鼠標,那么繪圖會大大滯后於光標(追逐它)。

為了重現/測試問題,我嘗試生成盡可能精簡的代碼。 然而,由於渲染延遲,在光標和矩形之間仍然存在明顯的差距,即使在具有不錯規格的計算機上(Chrome Beta 37,Fedora 20,i7 4770k等)

任何人都可以為這個原因做出貢獻,或建議改進以下代碼以減少延遲:

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();

這有一點點延遲,但在真正的應用程序中沒用:

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);
}

鼠標指針總是比繪圖更快,所以最好的選擇不是讓用戶的眼睛有理由感知延遲:

在用戶繪圖時關閉鼠標光標。

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

移動的矩形將用作鼠標光標,但如果用戶需要可視指南,您可以:

還使用幾行繪制十字准線。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM