我需要为我正在处理的画布应用程序添加触摸功能(多个用户白板),我已经阅读了有关事件监听器和event.preventDefault()
,但我无法理解我可以使用'DOMContentLoaded'和'touchmove'两个事件监听器。此时我不知道使用多个事件监听器是否是我需要的解决方案。
这是我正在使用的代码:
document.addEventListener("DOMContentLoaded", function() {
var mouse = {
click: false,
move: false,
pos: {x:0, y:0},
pos_prev: false
};
var canvas = document.getElementById('drawing');
var context = canvas.getContext('2d');
var width = 1280;
var height = 960;
var socket = io.connect();
var lineWidth = 1;
var shadowBlur = 1;
var shadowColor = "black";
var strokeStyle = "black";
canvas.width = width;
canvas.height = height;
canvas.onmousedown = function(e){ mouse.click = true; };
canvas.onmouseup = function(e){ mouse.click = false; };
canvas.onmousemove = function(e) {
mouse.pos.x = e.clientX / width;
mouse.pos.y = e.clientY / height;
mouse.move = true;
};
socket.on('draw_line', function (data) {
var line = data.line;
context.beginPath();
context.lineWidth = lineWidth;
context.shadowBlur = shadowBlur;
context.strokeStyle = strokeStyle;
context.lineJoin="round";
context.lineCap = "round";
context.moveTo(line[0].x * width, line[0].y * height);
context.lineTo(line[1].x * width, line[1].y * height);
context.stroke();
});
function mainLoop() {
if (mouse.click && mouse.move && mouse.pos_prev) {
socket.emit('draw_line', { line: [ mouse.pos, mouse.pos_prev ] });
mouse.move = false;
}
mouse.pos_prev = {x: mouse.pos.x, y: mouse.pos.y};
setTimeout(mainLoop, 50);
}
mainLoop();
});
我真的很感激任何帮助。
感谢。
答案 0 :(得分:0)
你遇到某种错误吗?现在,您的代码似乎通过侦听单击鼠标并移动鼠标来进行操作。如果按下鼠标,则移动鼠标并且循环至少运行一次(mouse.click&& mouse.move&& mouse.pos_prev)然后它在canvas元素上绘制一条线。 / p>