blob: aaaa39776c1cb3bed437b29109a7cb8eda3fadbc (
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
|
const canvas = document.getElementById('drawing-board');
const ctx = canvas.getContext('2d');
const canvasOffsetX = canvas.offsetLeft;
const canvasOffsetY = canvas.offsetTop;
canvas.width = window.innerWidth - canvasOffsetX * 2;
canvas.height = window.innerHeight - canvasOffsetY * 2;
let isPainting = false;
let lineWidth = 5;
let strokeColor = "skyblue"
let drawings = [];
ctx.strokeStyle = strokeColor;
const draw = (e) => {
if (!isPainting) {
return;
}
ctx.lineWidth = lineWidth;
ctx.lineCap = 'round';
ctx.lineTo(e.pageX - canvasOffsetX, e.pageY - canvasOffsetY);
drawings.push({x : (e.pageX - canvasOffsetX)/canvas.width, y : (e.pageY - canvasOffsetY)/canvas.height});
ctx.stroke();
}
canvas.addEventListener('mousedown', (e) => {
isPainting = true;
});
canvas.addEventListener('mouseup', (e) => {
isPainting = false;
drawings.push({x : -1, y : -1})
ctx.stroke();
ctx.beginPath();
});
canvas.addEventListener('mousemove', draw);
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;
|