Canvas触摸支持,定位触摸事件

Canvas touch support, positioning the touch event

有什么问题

我正在使用 Vuejs 构建一种绘图应用程序。这样做时我遇到了触摸事件定位的问题。我的意思是,每次我尝试在浏览器中使用触摸模拟绘制一些东西时,都会在触摸点下方约 300 像素处绘制线条。此代码无需触摸模拟即可完美运行,但不幸的是我需要触摸支持。感谢您的各种帮助!

Canvas 在 DOM

<tempalte>
    <canvas ref="Canvas" id="canvas" width="350" height="350">
</template>

Canvas在vue模板中

const Canvas = ref('');

    
const state = reactive({
      canvas: '',
      isDrawing: false,
      X: '',
      Y: '',
    })

onMounted(() => {
      let canvas = document.querySelector('#canvas')
      let context = canvas.getContext('2d')
      state.canvas = context
      Canvas.value.addEventListener('touchstart', beginTouchDrawing, false);
      Canvas.value.addEventListener('touchmove', TouchDrawing, false);
    })

事件函数

function beginTouchDrawing(event) {
      state.isDrawing = true
      let pos = touchPose(event)
      drawLine(pos[0], pos[1])
      state.X = pos[0];
      state.Y = pos[1];
      event.preventDefault();
    }

    
function touchPose(e){
        if (e.touches) {
          if (e.touches.length === 1) { // Only deal with one finger
              let touch = e.touches[0]; // Get the information for finger #1
              return [touch.pageX - touch.target.offsetLeft,
              touch.pageY - touch.target.offsetTop]
          }
        }
    }


    
function TouchDrawing(event) {
      if (state.isDrawing) {
        let pose = touchPose(event)
        drawLine(state.X, state.Y, pose[0], pose[1]);
        state.X = pose[0];
        state.Y = pose[1];
        event.preventDefault();
      }
    }

画线

function drawLine(X, Y, newX, newY){
      let ctx = state.canvas
      ctx.lineWidth = 10;
      ctx.beginPath();
      ctx.moveTo(X, Y);
      ctx.lineTo(newX, newY);
      ctx.stroke();
      ctx.closePath();
      ctx.lineCap = 'round';
    }

感谢您的帮助!!

要获得 canvas 位置,您必须将所有 canvas parents

的 offsetTop/offsetLeft 求和
function touchPose(e){
    if (e.touches) {
      if (e.touches.length === 1) { // Only deal with one finger
          let touch = e.touches[0]; // Get the information for finger #1
          let offset = getOffsetSum(touch.target);
          return [touch.pageX - offset.x,
          touch.pageY - offset.y]
      }
    }
}

function getOffsetSum(element) {
    var curleft = 0, curtop = 0;

    if (element.offsetParent) {
        do {
            curleft += element.offsetLeft;
            curtop  += element.offsetTop;
            element = element.offsetParent;
        } while (element);
    }

    return { x: curleft, y: curtop };
}