【发布时间】:2019-12-10 15:32:05
【问题描述】:
嘿,我的画布以及它如何处理触摸事件有问题,目前它可以正常处理鼠标事件和按预期绘图但是当我尝试合并触摸事件时它确实有点工作但是当我触摸画布时输出固定在左上角,让我相信偏移量已经过时了,老实说,我真的不知道从这里去哪里,所以任何帮助都会非常有用。
$( 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,这让我很生气。任何帮助都会得到帮助。
【问题讨论】:
标签: javascript html canvas touch offset