Seymour
Seymour

Reputation: 3

Canvas tactile JS

I have a project where I need to build a website of bicycles reservation.I need to create a canvas to allow people to sign things. I create my canvas and it works well with mouse, but I need to know how to do it on a mobile device. I tried several things (with touchmove/touchstart) but I can't get it working. This is my object canvas in ES6 (I don't use jQuery). I'm not allowed to use any libraries, and I want to use only JS (I'll learn jQuery at some point).

class Canvas {

    constructor(canvasId, clearBtnId) {
        this.canvas = document.getElementById(canvasId);
        this.idBtnClear = clearBtnId;
        this.ctx = this.canvas.getContext("2d");
        this.painting = false;
        this.isEmpty = true;

        this.canvas.addEventListener("mousedown", this.mouseDown.bind(this));
        this.canvas.addEventListener("mouseup", this.mouseUp.bind(this));
        this.canvas.addEventListener("mousemove", this.draw.bind(this));
        this.canvas.addEventListener("mouseout", this.mouseUp.bind(this));

        document.getElementById(this.idBtnClear).addEventListener("click", this.clearCanvas.bind(this));

    }

    mouseDown(e) {
        this.painting = true;
    }

    mouseUp() {
        this.painting = false;
        this.ctx.beginPath();
    }

    draw(e) {
        if (!this.painting) return;
        this.ctx.lineWidth = 5;
        this.ctx.lineCap = "round";
        this.ctx.lineJoin = "round";

        let topPos = e.pageY - this.canvas.offsetTop;
        let leftPos = e.pageX - this.canvas.offsetLeft;

        this.ctx.lineTo(leftPos, topPos);
        this.ctx.stroke();
        this.ctx.beginPath();
        this.ctx.moveTo(leftPos, topPos);

        this.isEmpty = false;
    }

    clearCanvas() {
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        this.isEmpty = true;
    }

}

Upvotes: 0

Views: 126

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386680

You could use the events

for touch devices.

Upvotes: 1

Related Questions