I am facing an issue with my painting app where it works perfectly on desktop browsers but fails to function on mobile devices. I tried adding event listeners for mobile events, which are understood by mobile devices, but unfortunately, that did not solve the problem. Any suggestions on how I can troubleshoot and fix this issue?
Here is the link to the app: https://codepen.io/sp2012/pen/oNWeZBx
Below is the code for reference:
HTML
<input type="color" class="js-color-picker color-picker">
<input type="range" class="js-line-range" min="1" max="72" value="1">
<label class="js-range-value">1</label>Px
<canvas class="js-paint paint-canvas" width="200" height="200"></canvas>
CSS
.paint-canvas {
border: 1px black solid;
display: block;
margin: 1rem;
}
.color-picker {
margin: 1rem 1rem 0 1rem;
}
JS
const paintCanvas = document.querySelector( '.js-paint' );
const context = paintCanvas.getContext( '2d' );
context.lineCap = 'round';
const colorPicker = document.querySelector( '.js-color-picker');
colorPicker.addEventListener( 'change', event => {
context.strokeStyle = event.target.value;
} );
const lineWidthRange = document.querySelector( '.js-line-range' );
const lineWidthLabel = document.querySelector( '.js-range-value' );
lineWidthRange.addEventListener( 'input', event => {
const width = event.target.value;
lineWidthLabel.innerHTML = width;
context.lineWidth = width;
} );
let x = 0, y = 0;
let isMouseDown = false;
const stopDrawing = () => { isMouseDown = false; }
const startDrawing = event => {
isMouseDown = true;
[x, y] = [event.offsetX, event.offsetY];
}
const drawLine = event => {
if ( isMouseDown ) {
const newX = event.offsetX;
const newY = event.offsetY;
context.beginPath();
context.moveTo( x, y );
context.lineTo( newX, newY );
context.stroke();
//[x, y] = [newX, newY];
x = newX;
y = newY;
}
}
paintCanvas.addEventListener( 'mousedown', startDrawing );
paintCanvas.addEventListener( 'mousemove', drawLine );
paintCanvas.addEventListener( 'mouseup', stopDrawing );
paintCanvas.addEventListener( 'mouseout', stopDrawing );
paintCanvas.addEventListener("touchstart", startDrawing);
paintCanvas.addEventListener("touchend", stopDrawing);
paintCanvas.addEventListener("touchcancel", stopDrawing);
paintCanvas.addEventListener("touchmove", drawLine);