嘿,所以我的触摸事件偏移量有问题,可以用鼠标在画布上绘制,但是用触摸板偏移量在角落很远,当我触摸画布时,它会“绘制”触摸板,但就像我说的那样。我知道我的偏移量不见了,但是我是一个JavaScript新手,并且一直在尝试调试几个小时
$( 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';
};
}
});
要么是onTouchPaint要么是touchmove,这正在杀死我。任何帮助都可以申请。