Home  >  Q&A  >  body text

javascript - How to get the coordinates of the touch event in the canvas in native canvas?

When canvas responds to the mousedown event, it can extract the internal coordinates of the element through event.offsetX and offsetY. Then I changed to touchstart and there is no offsetX and offsetY. Where should I find the internal coordinates of the element?

黄舟黄舟2729 days ago694

reply all(3)I'll reply

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-24 11:38:27

    The algorithm processed in my canvas map library Sinomap is this (with changes):

    // 注意这里是为 canvas 的 DOM 元素增加 Listener 而非 canvas 的 ctx
    document
      .getElementById('my-canvas')
      .addEventListener('click', updateHandler, false)
    
    function updateHandler (e) {
      // canvas 为你的 canvas ctx 变量
      const box = canvas.getBoundingClientRect()
      const mouseX = (e.clientX - box.left) * canvas.width / box.width
      const mouseY = (e.clientY - box.top) * canvas.height / box.height
      console.log([mouseX, mouseY])
    }

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-24 11:38:27

    Touch event, you need to get e.touches[0].pageX or other coordinates. As for touchend, for compatibility reasons, it is best to use e.changedTouches

    reply
    0
  • 黄舟

    黄舟2017-05-24 11:38:27



    reply
    0
  • Cancelreply