There is a canvas on which an arbitrary line is drawn according to the movement of the mouse and the clamping of the left button.

It works only on a PC, on tablets and androids, instead of drawing lines by touching and navigating it on the screen of a mobile phone, a banal page scroll occurs.

The touch was a diva, that is, a block and drew on it and did not scroll the page on the android or tablet.

Please tell me what is needed for this?

  • Something similar is implemented in the Yandex map. When a finger hits it, it’s not the page that is scrolling, but the map, is it possible to somehow copy it from it? - Maxim
  • I think you need to look in the direction of the ascent of events. learn.javascript.ru/event-bubbling - dlarchikov

1 answer 1

Use the Event.preventDefault() method to stop the event from floating.
Then the event will not fall into the handlers of the parent element with scrollbars - and therefore, we will avoid unnecessary scrolling with a swipe.

 initDrawCanvas(document.getElementById('test')); function initDrawCanvas(cnv) { cnv.width = cnv.clientWidth; cnv.height = cnv.clientHeight; cnv.contextMain = cnv.getContext('2d'); cnv.linesArr = []; cnv.drawLines = function () { this.contextMain.clearRect(0, 0, this.width, this.height); this.contextMain.beginPath(); for (let line of this.linesArr) { if (!line.x2 || !line.y2) continue; this.contextMain.moveTo(line.x1, line.y1); this.contextMain.lineTo(line.x2, line.y2); } this.contextMain.stroke(); requestAnimationFrame(() => this.drawLines()); }; cnv.inputHandler = function (e) { let bcr = this.getBoundingClientRect(), x = (e.changedTouches[0].clientX || e.clientX) - bcr.left, y = (e.changedTouches[0].clientY || e.clientY) - bcr.top; switch (e.type) { case 'touchstart': case 'mousedown': this.linesArr.push({ x1: x, y1: y }); break; case 'touchmove': case 'mousemove': this.drawLines(); case 'touchend': case 'mouseup': let line = this.linesArr[this.linesArr.length - 1]; line.x2 = x; line.y2 = y; break; default: return; } e.preventDefault(); }; [ 'mousedown', 'mouseup', 'mousemove', 'touchstart', 'touchend', 'touchmove' ].forEach(evtName => cnv.addEventListener(evtName, cnv.inputHandler)); cnv.drawLines(); } 
 body { height: 200vh; } #test { width: 100%; height: 40%; border: 1px solid #ccc; } 
 <canvas id="test"></canvas> 

  • thanks, helped, figured out - Maxim