【发布时间】:2014-07-11 12:54:12
【问题描述】:
我试图为触摸优化设备制作多人绘图,我使用带有套接字 io 的节点 js 在画布上绘制点。但问题是,“在调用 touchend 事件后,它没有重置”,
为了清楚起见,请查看下面的这张图片。 需要红线,但下次触摸时会自动绘制蓝线
这是我的代码:
if (is_touch_device) {
var drawer = {
isDrawing: false,
touchstart: function (coors) {
prev.x = coors.x;
prev.y = coors.y;
context.beginPath();
context.moveTo(coors.x, coors.y);
this.isDrawing = true;
},
touchmove: function (coors) {
if($.now() - lastEmit > 5){
socket.emit('mousemove',{
'x': coors.x,
'y': coors.y,
'drawing': drawer.isDrawing,
'id': id,
'color': 'test'
});
lastEmit = $.now();
}
if (this.isDrawing) {
plot(prev.x, prev.y, coors.x, coors.y);
prev.x = coors.x;
prev.y = coors.y;
}
},
touchend: function (coors) {
if (this.isDrawing) {
this.isDrawing = false;
}
}
};
function draw(event) {
var coors = {
x: event.targetTouches[0].pageX,
y: event.targetTouches[0].pageY
};
var obj = sigCanvas;
if (obj.offsetParent) {
do {
coors.x -= obj.offsetLeft;
coors.y -= obj.offsetTop;
}
while ((obj = obj.offsetParent) != null);
}
drawer[event.type](coors);
}
节点绘图部分:
socket.on('moving', function (data) {
if(data.drawing && clients[data.id]){
plot(clients[data.id].x, clients[data.id].y, data.x, data.y);
}
clients[data.id] = data;
clients[data.id].updated = $.now();
});
绘图功能:
function plot(x1, y1, x2, y2)
{
var sigCanvas = document.getElementById("canvasSignature");
var context = sigCanvas.getContext("2d");
context.beginPath();
context.moveTo(x1, y1);
context.lineTo(x2, y2);
context.stroke();
}
脚本js:http://abnode.azurewebsites.net/script.js
我的节点js:http://abnode.azurewebsites.net/server.js
更新
socket.on('moving', function (data) {
if(data.drawing && clients[data.id] ){
// Problem is it gets plotted automatically from one point on touchend, its not stopped
drawLine(clients[data.id].x, clients[data.id].y, data.x, data.y);
}
clients[data.id] = data;
clients[data.id].updated = $.now();
});
function drawLine(fromx, fromy, tox, toy){
context.beginPath();
context.moveTo(fromx, fromy);
context.lineTo(tox, toy);
context.strokeStyle = "Black";
context.stroke();
}
【问题讨论】:
-
每个绘图都必须是“原子的”(完整的 beginPath + 路径命令 + 笔划),否则您的代码的多用户方面将失败,因为路径命令将混合在一起。通过在 mousemove/touchmove 中执行完整的 beginPath+draw+stroke 来重新设计。本地和远程绘图(对于此客户端和外部套接字客户端)都需要这种原子设计。祝你的项目好运! :-)
-
@markE 我试过鼠标工作正常但触摸没有关闭它的路径..问题出在客户端数组中,你能帮帮我吗? [以上更新代码]
标签: javascript jquery html node.js html5-canvas