我正在使用 Vuejs 构建一种绘图应用程序。这样做时,我遇到了触摸事件定位问题。我的意思是,每次我尝试在浏览器中使用触摸模拟绘制一些东西时,都会在触摸点下方约 300 像素处绘制线条。这段代码在没有触摸模拟的情况下完美运行,但不幸的是我需要触摸支持。感谢您的各种帮助!
discord.py
<tempalte>
<canvas ref="Canvas" id="canvas" width="350" height="350">
</template>
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();
}
}
答案 0 :(得分:1)
要获得画布位置,您必须对所有画布父级的 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 };
}