如何使画布绘图在移动设备上工作

时间:2017-05-13 21:11:45

标签: javascript jquery html5 canvas mobile

我的画布绘图界面在桌面上完美运行但无法在iPhone上运行。

当我尝试绘制时,它只是在我的拇指所在的位置。当我拖动拇指时,没有线条,页面继续滚动...

代码:

var clearButton = document.getElementById('doodle-bin');
var canvascontainer = document.getElementById('doodle-canvas-container');
var canvas = document.getElementById('doodle-canvas');
var context = canvas.getContext('2d');
var radius = (document.getElementById('doodle-canvas-container').clientWidth + document.getElementById('doodle-canvas-container').clientHeight) / 150;
var dragging = false;

function getMousePosition(e) {
    var mouseX = e.offsetX * canvas.width / canvas.clientWidth | 0;
    var mouseY = e.offsetY * canvas.height / canvas.clientHeight | 0;
    return {x: mouseX, y: mouseY};
}

context.mozImageSmoothingEnabled = false;
context.imageSmoothingEnabled = false;

canvas.width = 1280;
canvas.height = 720;
canvas.style.width = '100%';
canvas.style.height = '100%';

/* CLEAR CANVAS */
function clearCanvas() {
    context.clearRect(0, 0, canvas.width, canvas.height);
}

clearButton.addEventListener('click', clearCanvas);


var putPoint = function (e) {
    if (dragging) {
        context.lineTo(getMousePosition(e).x, getMousePosition(e).y);
        context.lineWidth = radius * 2;
        context.stroke();
        context.beginPath();
        context.arc(getMousePosition(e).x, getMousePosition(e).y, radius, 0, Math.PI * 2);
        context.fill();
        context.beginPath();
        context.moveTo(getMousePosition(e).x, getMousePosition(e).y);
    }
};

var engage = function (e) {
    dragging = true;
    putPoint(e);
};
var disengage = function () {
    dragging = false;
    context.beginPath();
};

canvas.addEventListener('mousedown', engage);
canvas.addEventListener('mousemove', putPoint);
canvas.addEventListener('mouseup', disengage);
document.addEventListener('mouseup', disengage);
canvas.addEventListener('contextmenu', disengage);

canvas.addEventListener('touchstart', engage, false);
canvas.addEventListener('touchmove', putPoint, false);
canvas.addEventListener('touchend', disengage, false);

任何帮助将不胜感激!谢谢

1 个答案:

答案 0 :(得分:0)

putPoint功能中取消默认事件和传播。

var putPoint = function (e) {
    e.preventDefault();
    e.stopPropagation();

    if (dragging) {
    ....

然后查看Using Touch Events with the HTML5 Canvas以处理如何将触摸坐标转换为鼠标坐标。

canvas.addEventListener("touchmove", function (e) {
  var touch = e.touches[0];
  var mouseEvent = new MouseEvent("mousemove", {
    clientX: touch.clientX,
    clientY: touch.clientY
  });
  canvas.dispatchEvent(mouseEvent);
}, false);