summaryrefslogtreecommitdiff
path: root/index.js
blob: ff30475ad41bb21df6e75b62894de2cb9567aae1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
const canvas = document.getElementById('drawing-board');
const ctx = canvas.getContext('2d');
const reset = document.getElementById("reset");

const canvasOffsetX = canvas.offsetLeft;
const canvasOffsetY = canvas.offsetTop;

canvas.width = window.innerWidth - canvasOffsetX * 2;
canvas.height = window.innerHeight - canvasOffsetY * 2;

reset.style.top = canvasOffsetY + "px";
reset.style.left = canvas.width - canvasOffsetX + "px";

let isPainting = false;
let lineWidth = 2;
let strokeColor = "red"
let drawings = [];

ctx.lineWidth = lineWidth;
ctx.lineCap = 'square';
ctx.strokeStyle = strokeColor;

const draw = (x, y) => {
    if (!isPainting) {
        return;
    }
    

    // ctx.lineTo(x - canvasOffsetX, y - canvasOffsetY);
    drawings.push({x : (x - canvasOffsetX)/canvas.width, y : (y - canvasOffsetY)/canvas.height});
    ctx.stroke();
    ctx.beginPath();
}

const drawCross = (x, y) => {
    ctx.moveTo(x - 5, y - 5);
    ctx.lineTo(x + 5, y + 5);
    ctx.moveTo(x + 5, y - 5);
    ctx.lineTo(x - 5, y + 5);
    ctx.stroke();
    ctx.beginPath();
    setTimeout( ()=>{
        ctx.fillStyle = "aliceblue";
        ctx.fillRect(x - 7, y - 7, 14, 14);
    }, 1 * 1000);
}

canvas.addEventListener('mousedown', (e) => {
    isPainting = true;

    drawCross(e.clientX - canvasOffsetX, e.clientY - canvasOffsetY);
});

/* canvas.addEventListener('mouseup', (e) => {
    isPainting = false;
    drawings.push({x : -1, y : -1})
    ctx.stroke();
    ctx.beginPath();
}); */

// canvas.addEventListener('mousemove', (e) => draw(e.clientX, e.clientY));

canvas.addEventListener('touchstart', (e) => {
    isPainting = true;
    draw(e.targetTouches[0].clientX, e.targetTouches[0].clientY);
});

/* canvas.addEventListener('touchend', (e) => {
    isPainting = false;
    drawings.push({x : -1, y : -1})
    ctx.stroke();
    ctx.beginPath();
}); */

// canvas.addEventListener('touchmove', (e) => draw(e.targetTouches[0].clientX, e.targetTouches[0].clientY));

function redrawCanvas() {
    canvas.width = window.innerWidth - canvasOffsetX * 2;
    canvas.height = window.innerHeight - canvasOffsetY * 2;
    ctx.strokeStyle = strokeColor;
    ctx.lineWidth = lineWidth;
    ctx.lineCap = 'round';
    drawings.forEach(element => {
        if (element.x >= 0 && element.y >= 0){
            ctx.lineTo(element.x * canvas.width, element.y * canvas.height);
            ctx.stroke();
        }
        else {
            ctx.stroke();
            ctx.beginPath();
        }
    });
}

window.onresize = redrawCanvas;