javascript - How to get the coordinates of the touch event in the canvas in native canvas?
黄舟
黄舟 2017-05-24 11:36:27
0
3
691

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?

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(3)
曾经蜡笔没有小新

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])
}
过去多啦不再A梦

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

黄舟



Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!