Javascript Canvas触摸事件

时间:2019-12-10 15:32:05

标签: javascript html canvas touch offset

嘿,我的画布及其如何处理触摸事件存在问题,目前它可以按预期与鼠标事件和绘图配合使用,但是当我尝试合并触摸事件时,它确实可以工作,但是当我在画布上触摸输出时固定在左上角,使我相信偏移量已经消失了,说实话,我真的不确定从哪里走,所以将大力寻求帮助。

$( document ).ready(function() {

  var container = document.getElementById('canvas');
  init(container, 200, 200, '#ddd');


  function init(container, width, height, fillColor) {
    var canvas = createCanvas(container, width, height);
    var ctx = canvas.getContext('2d');


    var mouse = {x: 0, y: 0};
    var touch = {x: 0, y: 0};
    var last_mouse = {x: 0, y: 0};
    var last_touch = {x: 0, y: 0};


    canvas.addEventListener('mousemove', function(e) {
      last_mouse.x = mouse.x;
      last_mouse.y = mouse.y;


      if (e.offsetX) {
        mouse.x = e.offsetX;
        mouse.y = e.offsetY;
      }
    });    

    canvas.addEventListener('touchmove', function(e) {
      var touch = e.touches[0];
      last_touch.x = e.pageX - touch.offsetLeft;
      last_touch.y = e.pageY - touch.offsetTop;


      if (e.offsetX) {
        touch.x = e.offsetX;
        touch.y = e.offsetY;
      }
    });  

    canvas.onmousemove = function(e) {

      var x = e.pageX - this.offsetLeft;
      var y = e.pageY - this.offsetTop;
    };

    canvas.addEventListener('touchstart', function(e) {
      canvas.addEventListener('touchmove', onTouchPaint, false);
    }, false);

    canvas.addEventListener('mousedown', function(e) {
      canvas.addEventListener('mousemove', onPaint, false);
    }, false);
    canvas.addEventListener('mouseup', function() {
      canvas.removeEventListener('mousemove', onPaint, false);
    });

    var onPaint = function() {
      ctx.beginPath();
      ctx.moveTo(last_mouse.x, last_mouse.y);
      ctx.lineTo(mouse.x, mouse.y);
      ctx.closePath();
      ctx.stroke();

      ctx.lineWidth = 15 ;
      ctx.lineJoin = 'round';
      ctx.lineCap = 'round';
      ctx.strokeStyle = 'black';
    };

    var onTouchPaint = function() {
      ctx.beginPath();
      ctx.moveTo(last_touch.x, last_touch.y);
      ctx.lineTo(touch.x, touch.y);
      ctx.closePath();
      ctx.stroke();

      ctx.lineWidth = 15 ;
      ctx.lineJoin = 'round';
      ctx.lineCap = 'round';
      ctx.strokeStyle = 'black';
    };
  } 
});

要么是onTouchPaint要么是touchmove,这正在杀死我。任何帮助都可以申请。

1 个答案:

答案 0 :(得分:0)

以下内容应从事件中获得正确的触摸或单击位置。我本人确实为此付出了很多努力,而这终于成功了。基本上,这是从stackoverflow上其他答案中摘录的合并内容。诀窍应该是适当考虑画布的getBoundingClientRect

function getInteractionLocation(event) {
    let pos = { x: event.clientX, y: event.clientY };
    if (event.touches) {
        pos = { x: event.touches[0].clientX, y: event.touches[0].clientY };
    }
    const rect = event.target.getBoundingClientRect();
    const x_rel = pos.x - rect.left;
    const y_rel = pos.y - rect.top;
    const x = Math.round((x_rel * event.target.width) / rect.width);
    const y = Math.round((y_rel * event.target.height) / rect.height);
    return [x, y];
};