Javascript Canvas 触摸事件



嘿,我的画布以及它如何处理触摸事件有问题,目前它可以正常工作鼠标事件并按预期绘制,但是当我尝试合并触摸事件时,它确实有些工作,但是当我触摸画布时,输出固定在左上角,导致我相信偏移量很远,老实说,我真的不确定从这里开始,所以任何帮助将得到极大的赞赏。

$( 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';
};
} 
});

它要么是TouchPaint,要么是touchmove,它正在杀死我。任何帮助都是值得赞赏的。

以下内容应从事件中获得正确的触摸或单击位置。我自己确实和这个斗争过很多,这终于成功了。它基本上是从堆栈溢出上的其他答案中截取而来的合并。诀窍应该是正确考虑画布的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];
};

最新更新