画布触摸事件js

时间:2019-10-11 08:32:04

标签: javascript canvas touch

嗨,我需要我的画布帮助,我尝试了多种方法来使它在移动设备上工作,但我做不到。 我尝试启动创建的方法来启动和停止click事件。但是我认为这不是严格的方法。

class Canvas {
  constructor(emplacement, btnEffacer, btnCroix) {
    //btn pour effacer et afficher
    this.btnCroix = document.querySelector(".fermeture")
    this.btnEffacer = document.querySelector(btnEffacer);
    // emplacement du canvas
    this.canvas = document.querySelector(emplacement);
    this.cont = this.canvas.getContext("2d");
    //quelques variables
    this.signer = false;
    this.vide = true
    this.canvas.width = 190;
    this.canvas.height = 120;
    this.cont.lineWidth = 2;
    this.cont.strokeStyle = "#000";

    //les evenements
    //comencer a dessigner
    this.canvas.addEventListener("touchstart", this.touchstart.bind(this), false);
    this.canvas.addEventListener("touchmove", this.touchmove.bind(this), false);
    this.canvas.addEventListener("touchend", this.touchend.bind(this), false);

    this.canvas.addEventListener("mousedown", this.demarrer.bind(this));
    //arreter de dessigner
    this.canvas.addEventListener("mouseup", this.arreter.bind(this));
    //le trece du dessin
    this.canvas.addEventListener("mousemove", this.dessiner.bind(this));
    //effacer le dessin
    this.btnCroix.addEventListener("click", this.effacer.bind(this));
    this.btnEffacer.addEventListener("click", this.effacer.bind(this));
  }
  //les methodes
  touchstart(e) {
    e.preventDefault()
    const touche = e.touches[0]
    this.demarrer(e)
  }

  touchmove(e) {
    e.preventDefault()
    const touche = e.touches[0]
    this.dessiner(e)
  }

  touchend(e) {
    e.preventDefault()
    this.arreter(e)
  }
  demarrer(e) {
    this.signer = true;
    this.vide = false
    this.dessiner(e);
  }

  arreter(e) {
    this.signer = false;
    this.cont.beginPath();
  }

  dessiner(e) {
    if (!this.signer) return;
    this.cont.lineTo(e.offsetX, e.offsetY);
    this.cont.stroke();
    this.cont.beginPath();
    this.cont.moveTo(e.offsetX, e.offsetY);
  }

  effacer() {
    this.cont.clearRect(0, 0, this.canvas.width, this.canvas.height);
    this.vide = true
  }

如果您可以向我解释它的工作原理并帮助我编写代码,那就太好了。

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

似乎您在触摸事件之前可能将关键字“ on”设置为“ on”。

代码中的以下三行:

this.canvas.addEventListener("touchstart", this.touchstart.bind(this), false);
this.canvas.addEventListener("touchmove", this.touchmove.bind(this), false);
this.canvas.addEventListener("touchend", this.touchend.bind(this), false);

实际上应该是:

this.canvas.addEventListener("ontouchstart", this.touchstart.bind(this), false);
this.canvas.addEventListener("ontouchmove", this.touchmove.bind(this), false);
this.canvas.addEventListener("ontouchend", this.touchend.bind(this), false);

https://www.w3schools.com/jsref/obj_touchevent.asp