-
Notifications
You must be signed in to change notification settings - Fork 0
/
script-aca.js
88 lines (72 loc) · 2.61 KB
/
script-aca.js
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
document.addEventListener('DOMContentLoaded', () => {
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let isDrawing = false;
let drawingData = [];
canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', endDrawing);
canvas.addEventListener('mouseout', endDrawing);
// Touch events
canvas.addEventListener('touchstart', handleTouchStart);
canvas.addEventListener('touchmove', handleTouchMove);
canvas.addEventListener('touchend', endDrawing);
function startDrawing(e) {
isDrawing = true;
const { offsetX, offsetY } = e;
drawingData.push({ type: 'start', x: offsetX, y: offsetY });
}
function draw(e) {
if (!isDrawing) return;
const { offsetX, offsetY } = e;
drawingData.push({ type: 'draw', x: offsetX, y: offsetY });
ctx.lineTo(offsetX, offsetY);
ctx.stroke();
}
function handleTouchStart(e) {
e.preventDefault();
const touch = e.touches[0];
const { pageX, pageY } = touch;
const offsetX = pageX - canvas.offsetLeft;
const offsetY = pageY - canvas.offsetTop;
startDrawing({ offsetX, offsetY });
}
function handleTouchMove(e) {
e.preventDefault();
const touch = e.touches[0];
const { pageX, pageY } = touch;
const offsetX = pageX - canvas.offsetLeft;
const offsetY = pageY - canvas.offsetTop;
draw({ offsetX, offsetY });
}
function endDrawing() {
isDrawing = false;
ctx.beginPath();
drawingData.push({ type: 'end' });
}
document.getElementById('clearBtn').addEventListener('click', () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawingData = [];
});
document.getElementById('replayBtn').addEventListener('click', () => {
if (drawingData.length === 0) return;
ctx.clearRect(0, 0, canvas.width, canvas.height);
let currentIndex = 0;
function replayDrawing() {
if (currentIndex >= drawingData.length) return;
const { type, x, y } = drawingData[currentIndex];
if (type === 'start') {
ctx.beginPath();
ctx.moveTo(x, y);
} else if (type === 'draw') {
ctx.lineTo(x, y);
ctx.stroke();
} else if (type === 'end') {
ctx.closePath();
}
currentIndex++;
requestAnimationFrame(replayDrawing);
}
replayDrawing();
});
});