在画布上使用触摸事件

时间:2021-06-12 03:32:04

标签: javascript html

我有一个程序可以用 JS 在 HTML 画布上绘图。它在鼠标上工作正常,但是当我在基于触摸的设备上尝试相同时,它只绘制一个点。我该如何解决这个问题?

这是处理鼠标事件的代码:

let m = document.getElementById('m-container');
const onMouseMove = (e) =>{
  m.style.left = e.pageX + 'px';
  m.style.top = e.pageY + 'px';
}
m.addEventListener('mousemove', draw);
m.addEventListener('mousedown', setPosition);
m.addEventListener('mouseenter', setPosition);
function setPosition(e) {
  pos.x = parseInt(document.getElementById('m-container').style.left, 10);
  pos.y = parseInt(document.getElementById('m-container').style.top, 10);
}
function draw(e) {
  // mouse left button must be pressed
  if (e.buttons !== 1 || isDragging) return;

    if(mode=="pen"){
        ctx.globalCompositeOperation="source-over";
    } else {
        ctx.globalCompositeOperation="destination-out";
    }
    
  ctx.beginPath(); // begin

  ctx.lineWidth = currentDrawWidth;
  ctx.lineCap = 'round';
  ctx.strokeStyle = currentDrawColour;
  ctx.moveTo(pos.x, pos.y); // from
  setPosition(e);
  ctx.lineTo(pos.x, pos.y); // to

  ctx.stroke(); // draw it!
}

这是处理触摸事件的代码:

m.addEventListener('touchmove', touchdraw);
m.addEventListener('touchstart', function (e) {
    setPositionTouch(e)
});
m.addEventListener('touchend', function (e) {
    setPositionTouch(e)
});
function setPositionTouch(e) {
  pos.x = e.clientX;
  pos.y = e.clientY;
}
function touchdraw(e) {
  
    if(mode=="pen"){
        ctx.globalCompositeOperation="source-over";
    } else {
        ctx.globalCompositeOperation="destination-out";
    }
    
  ctx.beginPath(); // begin

  ctx.lineWidth = currentDrawWidth;
  ctx.lineCap = 'round';
  ctx.strokeStyle = currentDrawColour;
  ctx.moveTo(pos.x, pos.y); // from
  setPositionTouch(e);
  ctx.lineTo(pos.x, pos.y); // to

  ctx.stroke(); // draw it!
}

mode 是单独声明的。

0 个答案:

没有答案