我正在尝试创建一个实时画布绘制工具(徒手绘制)。示例:只有一个人将在画布上绘画,而他的画将在N个客户画布上复制。问题是每个人的屏幕尺寸都不同,我需要按比例缩放。我可以实时遍历绘制点,然后在客户端中进行复制,但是我无法弄清楚如何在不变形的情况下以及在完全相同的位置缩放这些点(我有一个背景图片,并且在画布上做了覆盖元素,因此如果绘图的位置与绘图人的位置不同,则很明显比例尺不正确。
// 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;
答案 0 :(得分:1)
如果您还传输原始画布的尺寸,则可以在其他设备上计算出比例因子。
let scale = localCanvas.width / originalCanvas.width;
然后将此比例因子用于所有图形。
context.moveTo(coord.x * scale, coord.y * scale);
context.lineTo(nextCoord.x * scale, nextCoord.y * scale);
这假定画布大小是成比例的,并且背景恰好位于画布元素的后面。