实时 canvas 在不同屏幕尺寸上绘图

Real time canvas drawing on different screen sizes

我正在尝试创建实时 canvas 绘图工具(徒手绘图)。示例:只有一个人会在 canvas 上画画,他的画会复制到 N 个客户端 canvas 上。问题是每个人的屏幕尺寸不同,我需要相应地缩放。我可以实时传输绘图点,然后在客户端复制,但我不知道如何在不失真的情况下在完全相同的位置缩放这些点(我有一个背景图像,我用 canvas 元素,因此如果绘图与正在绘图的人不在同一位置,则很明显比例不正确)。

 // I have an observable that will receive the coordinates (coord[])
 // generated by the person who is responsible for the drawing.
 // The code below will only be executed for the person, who is 
 // watching, I can't figure out how to scale on the client screen...
 let currentX = parseFloat(coord[0]);
 let currentY = parseFloat(coord[1]);


 // if there is no previous points, then i'm starting at -1
 if (prevX == -1.0) {
    prevX = currentX;
 }

 if (prevY == -1.0) {
     prevY = currentY;
 }

 let pX = prevX * this.canvasEl.width/this.canvasEl.clientWidth;
 let pY = prevY * this.canvasEl.height/this.canvasEl.clientHeight;
 let cX = currentX * this.canvasEl.width/this.canvasEl.clientWidth;
 let cY = currentY * this.canvasEl.height/this.canvasEl.clientHeight;

 this.cx.beginPath();
 this.cx.moveTo(pX, pY);
 this.cx.lineTo(cX, cY);
 this.cx.stroke();

 prevX = currentX;

如果您还传输原始文件的大小canvas,那么您可以计算出其他设备上的比例因子。

let scale = localCanvas.width / originalCanvas.width;

然后对所有绘图使用此比例因子。

context.moveTo(coord.x * scale, coord.y * scale);
context.lineTo(nextCoord.x * scale, nextCoord.y * scale);

这假设 canvas 尺寸是成比例的并且背景恰好适合 canvas 元素。