簡體   English   中英

HTML Canvas:兩個客戶端同時編寫

[英]HTML Canvas: Two clients writing at the same time

我在使用nodejs作為客戶端之間的服務器實現在線 HTML5 Canvas時遇到了麻煩。

一個用戶可以單獨繪畫沒有問題,但當另一個客戶端進入並同時繪制時 ,會發生以下情況: 兩個客戶端的HTML5 Canvas問題

Client1是第一個客戶端鼠標的(X,Y)位置, Client2是第二個客戶端的(X,Y)位置。 因此,當第二個客戶端繪制時, 我的程序在兩點之間畫一條線

在這里,您可以瀏覽客戶端JS代碼,其中draw函數負責繪制從nodejs服務器接收的數據:

App.draw = function(x, y, type, color, clear) {

    if(clear != true) {

        App.ctx.strokeStyle = color;

        if (type === "dragstart") {

            App.ctx.beginPath();

    //alert("Me muevo a X: " + x + " e Y: " + y);

            return App.ctx.moveTo(x, y);

        } else if (type === "drag") {

            App.ctx.lineTo(x, y);

            return App.ctx.stroke();

        } else {

            return App.ctx.closePath();
        }

    } else {

        // Store the current transformation matrix
        App.ctx.save();

        // Use the identity matrix while clearing the canvas
        App.ctx.setTransform(1, 0, 0, 1, 0, 0);
        App.ctx.clearRect(0, 0, App.canvas.width, App.canvas.height);

        // Restore the transform
        App.ctx.restore();

    }

};

當您共享相同的路徑時,路徑將包含一組混合點,包括客戶端。

為避免這種情況,您可以使用以下兩種技術之一:

解決方案1

每次收到新點(每個客戶),完全完成一個筆畫。 這會將當前路徑減少到只有一個筆划:

App.ctx.beginPath();
App.ctx.moveTo(oldX, oldY);  /// previous point for this client
App.ctx.lineTo(x, y);
App.ctx.strokeStyle = color;
App.ctx.stroke();

解決方案2

使用兩個相互疊加的畫布。 為每個客戶分配一個圖層。 這樣,它們完全相互獨立,如果需要,可以將結果合並為一個,如果需要將結果保存為圖像:

HTML:

<div class="wrapper">
    <canvas id="client1" ... ></canvas>
    <canvas id="client2" ... ></canvas>
</div>

CSS:

.wrapper {
    position:relative;
    }
.wrapper > canvas {
    position:absolute;
    left:0;
    top:0;
    }

然后使用分配給每個客戶端的不同上下文變量 一種方法是:

App.ctx = [ctx1, ctx2];

然后在你的函數中使用參數client作為索引(在這種情況下為0或1):

App.draw = function(client, x, y, type, color, clear) {

    if(clear != true) {

        App.ctx[client].strokeStyle = color;

        if (type === "dragstart") {

            App.ctx[client].beginPath();

    //alert("Me muevo a X: " + x + " e Y: " + y);

            return App.ctx[client].moveTo(x, y);

        } else if (type === "drag") {

            App.ctx[client].lineTo(x, y);
            App.ctx[client].stroke();     /// this has no return value

            return;

        } else {

            App.ctx[client].closePath();
            return
        }

    } else {

        // Store the current transformation matrix
        App.ctx[client].save();

        // Use the identity matrix while clearing the canvas
        App.ctx[client].setTransform(1, 0, 0, 1, 0, 0);
        App.ctx[client].clearRect(0, 0, App.canvas.width, App.canvas.height);

        // Restore the transform
        App.ctx[client].restore();
    }
};

希望這可以幫助。

暫無
暫無

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

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