Search code examples
javascripthtml5-canvastouch-event

canvas draw touch is not drawing


if I enter a position on lineTo() and moveTo() i have a line but if i give the touchstart and touchmove position nothing happens and i have bot console erreur to help me

touchStart(e){
  this.touchDessiner(e.changedTouches[0].pageX, e.changedTouches[0].pageY)
  console.log(e.changedTouches[0].pageX, e.changedTouches[0].pageY);
}
touchMove(e){
  e.preventDefault();
  this.touchDessiner(e.changedTouches[0].pageX, e.changedTouches[0].pageY)
  console.log(e.changedTouches[0].pageX, e.changedTouches[0].pageY)
}

  touchDessiner(x, y){
    this.cont.lineWidth = 2;
    this.cont.strokeStyle = "#000";
    this.cont.beginPath();
    this.cont.moveTo(x, y);
    this.cont.lineTo(x, y);
    this.cont.stroke();
  }

thanks for your help


Solution

  • Here is the correct order to draw lines:

    On TouchStart:
    1. start a new path (lift the pen from the canvas)
    2. move the pen here

    On TouchMove:
    3. with the pen still touching the canvas, move the pen here

    canvas = document.getElementById("can");
    cont = canvas.getContext("2d");
    
    function touchStart(e){
      this.cont.beginPath();
      this.cont.moveTo(e.changedTouches[0].pageX, e.changedTouches[0].pageY);
    }
    
    function touchMove(e){
      e.preventDefault();
      this.touchDessiner(e.changedTouches[0].pageX, e.changedTouches[0].pageY)
    }
    
    function touchDessiner(x, y){
      this.cont.lineWidth = 2;
      this.cont.strokeStyle = "#000";
      this.cont.lineTo(x, y);
      this.cont.stroke();
    }
    
    window.addEventListener("touchstart", touchStart);
    window.addEventListener("touchmove", touchMove);
    <!DOCTYPE html>
    <html>
    <body>
      
      canvas
      <canvas id = "can" style = "border: 1px solid black; position:absolute; left:0px; top:0px;"> </canvas>
    
    </body>
    </html>