1

I created a canvas element in an HTML file and I want to draw a circle at the location in the canvas where a user touches it. I tried the following code but it does not work. It does draw a circle when I touch the canvas, but the circles are drawn at totally different locations than where the finger touches the canvas.

var ongoingTouches = [];

function startup() {
  var myCanvas = document.getElementById("myCanvas");
  
  myCanvas.addEventListener("touchstart", handleStart, false);
  myCanvas.addEventListener("touchend", handleEnd, false);
  myCanvas.addEventListener("touchcancel", handleCancel, false);
  myCanvas.addEventListener("touchmove", handleMove, false);
}

function colorForTouch(touch) {
  var r = touch.identifier % 16;
  var g = Math.floor(touch.identifier / 3) % 16;
  var b = Math.floor(touch.identifier / 7) % 16;
  
  r = r.toString(16);
  g = g.toString(16);
  b = b.toString(16);
  
  var color = "#" + r + g + b;
  
  return color;
}

function copyTouch({ identifier, pageX, pageY }) {
  return {
    identifier,
    pageX,
    pageY
  };
}

function handleStart(e) {
  e.preventDefault();
  
  var myCanvas = document.getElementById("myCanvas");
  var ctx = myCanvas.getContext("2d");
  var touches = e.changedTouches;
  var rec = myCanvas.getBoundingClientRect();
  
  for (var i = 0; i < touches.length; i++) {
    ongoingTouches.push(copyTouch(touches[i]));
    
    var color = colorForTouch(touches[i]);
    
    ctx.beginPath();
    ctx.arc(touches[i].clientX - rec.left, touches[i].clientY - rec.top, 4, 0, 2 * Math.PI, false);
    ctx.fillStyle = color;
    ctx.fill();
  }

}

function handleEnd(e) {}

function handleEnd(e) {}

function handleCancel(e) {}

function handleMove(e) {}

document.addEventListener("DOMContentLoaded", startup);
#myCanvas {
  width: 600px;
  height: 600px;
  background-color: bisque;
  border: solid black 1px;
}
<h1>The TouchEvent</h1>
<canvas id="myCanvas"></canvas>

Could you please help me?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Nick
  • 43
  • 3
  • Only responds to touch events, (Most browser dev tools can simulate if you need to: on Chrome Windows for example, F12, Ctrl+Shift+M). And touch near the top-left corner to see the scaling problem. – Wyck Oct 31 '21 at 05:35
  • 1
    Don’t set the width and height of your canvas in CSS! Set it as attributes instead. See [Canvas is stretched when using CSS but normal with "width" / "height" properties](/q/2588181/4642212) and [Sizing the canvas using CSS versus HTML](//developer.mozilla.org/docs/Web/HTML/Element/canvas#sizing_the_canvas_using_css_versus_html). In fact, removing the CSS properties and replacing them by the appropriate attributes appears to fix the issue. Also, note that you have `function handleEnd(e) {}` twice. – Sebastian Simon Oct 31 '21 at 05:35

0 Answers0