我的应用程序存在问题,允许人们在同一画布上绘制线条。目前,我的应用程序只在本地工作。当我打开多个页面时,应用程序工作正常,每个画布上都有相同的图形。但是,当在另一个选项卡中缩小或打开页面时,此页面不具有相同的画布,此画布上应显示的大多数行都将丢失。 为了在每次添加一行时重现画布的内容,我使用canvas方法DrawImage()。
以下是客户端的代码:
var url = 'http://localhost:4000';
var socket = io.connect(url);
var mouseData= {};
var startLine= false;
var first= {};
var last= {};
var tmpPosition= {};
var canvas = document.getElementById('tableauBlanc');
var contextCanvas1 = canvas.getContext('2d');
var Images = new Image();
var data;
canvas.addEventListener('mousemove', function(MouseEvent) {
tmpPosition=.x = MouseEvent.clientX;
tmpPosition=.y = MouseEvent.clientY;
tmpPosition== adaptMousePosition(tmpPosition=.x, tmpPosition=.y);
if (startLine) {
socket.emit('deleteAndRedrawCanvas', Images);
mouseData.px = first.x;
mouseData.py = first.y;
mouseData.dx = tmpPosition=.x;
mouseData.dy = tmpPosition=.y;
mouseData.validate= false;
socket.emit('DrawLine', mouseData);
}
}
});
canvas.addEventListener('click', function(MouseEvent) {
if (startDroite) {
last.x = MouseEvent.clientX;
last.y = MouseEvent.clientY;
last= adaptMousePosition(last.x, last.y);
contextCanvas1.strokeStyle = "#FF0000";
mouseData.px = first.x;
mouseData.py = first.y;
mouseData.dx = last.x;
mouseData.dy = last.y;
mouseData.validate= true;
socket.emit('DrawLine', mouseData);
startLine= false;
} else {
first.x = MouseEvent.clientX;
first.y = MouseEvent.clientY;
first= adaptMousePosition(first.x, first.y);
startLine= true;
}
});
socket.on('Draw', function(mouseData) {
contextCanvas1.strokeStyle = "#FF0000";
DrawLine(mouseData.px, mouseData.py, mouseData.dx, mouseData.dy);
if (mouseData.fini == true) {
setTimeout(DrawCanvas, 20);
}
});
function DrawCanvas() {
data = canvas.toDataURL();
Images.src = data;
Images.onload = function() {
Images.src = data;
contextCanvas1.drawImage(Images, 0, 0, 500, 500);
}
}
function DrawLine(px, py, dx, dy) {
contextCanvas1.strokeStyle = "#FF0000";
contextCanvas1.moveTo(px, py);
contextCanvas1.lineTo(dx, dy);
contextCanvas1.stroke();
}
socket.on('deleteAndRedrawCanvas', function(Images) {
contextCanvas1.clearRect(0, 0, 500, 500);
contextCanvas1.beginPath();
});
function adaptMousePosition(posX, posY) {
var gap= canvas.getBoundingClientRect();
return {
x: posX - gap.left,
y: posY - gap.top
};
}
感谢任何建议。 顺便说一下,这是我第一次使用Javascript和NodeJS,我的代码可能结构糟糕。