Draw touches on a canvas as circles
by musicreader
HTML
<canvas id="touchCanvas" width="400" height="400"></canvas>
CSS
canvas {
border: 1px solid black;
touch-action: none; /* Prevent default touch behaviors */
}
JavaScript
const canvas = document.getElementById('touchCanvas');
const ctx = canvas.getContext('2d');
canvas.addEventListener('touchstart', handleTouchStart, false);
canvas.addEventListener('touchmove', handleTouchMove, false);
canvas.addEventListener('touchend', handleTouchEnd, false);
function handleTouchStart(event) {
event.preventDefault();
drawTouches(event.targetTouches);
}
function handleTouchMove(event) {
event.preventDefault();
drawTouches(event.targetTouches);
}
function handleTouchEnd(event) {
event.preventDefault();
clearCanvas();
drawTouches(event.targetTouches);
}
function drawTouches(touches) {
clearCanvas();
for (let i = 0; i < touches.length; i++) {
const touch = touches[i];
const rect = canvas.getBoundingClientRect();
drawCircle(touch.clientX - rect.left, touch.clientY - rect.top, 20, i);
}
}
function drawCircle(x, y, radius, index) {
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.fillStyle = 'rgba(0, 150, 255, 0.5)';
ctx.fill();
ctx.stroke();
ctx.fillStyle = 'black';
ctx.fillText(`Touch ${index}`, x - 15, y - 25);
}
function clearCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}