简体   繁体   中英

How can I make canvas drawing work on mobile

My canvas drawing interface works perfectly on desktop but fails to work on iPhone.

When I try to draw, it just makes a dot where my thumb goes. When I drag my thumb, there is no line and the page continues to scroll...

Code:

 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); 

Any help would be greatly appreciated! Thank you

In your putPoint function cancel the default events and propagation.

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

    if (dragging) {
    ....

Then look at Using Touch Events with the HTML5 Canvas to handle how to convert your touch coordinates to mouse coordinates.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM