我同时使用画布与其他人绘画。但是这些行断了,如何在代码中修复它?
socket.on('drawLine', (data) => {
const line = data.line;
context.beginPath();
context.moveTo(line[0].axisX * width, line[0].axisY * height);
context.lineTo(line[1].axisX * width, line[1].axisY * height);
context.stroke();
});
function mainLoop() {
if (mouseSettings.click && mouseSettings.move &&
mouseSettings.previousPosition) {
socket.emit('drawLine', {line: [mouseSettings.position,
mouseSettings.previousPosition]});
mouseSettings.move = false;
}
mouseSettings.previousPosition = {axisX: mouseSettings.position.axisX,
axisY: mouseSettings.position.axisY};
setTimeout(mainLoop, 25);
}
mainLoop();
服务器Node.JS
app.use(express.static(__dirname + '/public'));
let historyPicture = [];
io.on('connection', (socket) => {
for (let index in historyPicture) {
socket.emit('drawLine', {line: historyPicture[index]});
}
socket.on('drawLine', (data) => {
historyPicture.push(data.line);
io.emit('drawLine', {line: data.line});
});
});
答案 0 :(得分:0)
使用其他lineCap
。画线之前,
context.lineCap = 'round';
默认的线帽"butt"
恰好在端点处使线平方。当您绘制沿另一方向移动的下一条线时,它将以不同的角度平方开,从而创建您所看到的间隙。 "round"
线帽在端点处“绘制一个圆圈”。由于圆是旋转对称的,因此不会产生间隙。
let context = document.getElementById('thin').getContext('2d');
drawLines(context);
context = document.getElementById('butt').getContext('2d');
context.lineWidth = 20;
drawLines(context);
context = document.getElementById('round').getContext('2d');
context.lineWidth = 20;
context.lineCap = 'round';
drawLines(context);
function drawLines (context) {
const path = [[0, 0], [0, 30], [30, 30], [30, 0], [60, 0], [60, 30]];
context.translate(30, 30);
for (let i = 0; i < path.length - 1; ++i) {
context.beginPath();
context.moveTo(path[i][0], path[i][1]);
context.lineTo(path[i + 1][0], path[i + 1][1]);
context.stroke();
}
context.setTransform(1, 0, 0, 1, 0, 0);
}
figure{display:inline-block;margin:0 10px;}figcaption{text-align:center;}
<figure>
<figcaption>Thin lines</figcaption>
<canvas id="thin" width="120" height="90"></canvas>
</figure>
<figure>
<figcaption>Default cap (butt)</figcaption>
<canvas id="butt" width="120" height="90"></canvas>
</figure>
<figure>
<figcaption>Round cap</figcaption>
<canvas id="round" width="120" height="90"></canvas>
</figure>