-
Notifications
You must be signed in to change notification settings - Fork 3
/
scribble.js
85 lines (69 loc) · 2.13 KB
/
scribble.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
const canvas = document.getElementById("canvas");
canvas.width = window.innerWidth - 700;
canvas.height = 300;
let context = canvas.getContext("2d");
let start_background_color = "white";
context.fillStyle = start_background_color;
context.fillRect(0, 0, canvas.width, canvas.height);
let draw_color = "black";
let draw_width = "2";
let is_drawing = false;
let restore_array = [];
let index = -1;
function change_color(element) {
draw_color = element.style.background;
}
canvas.addEventListener("touchstart", start, false);
canvas.addEventListener("touchmove", draw, false);
canvas.addEventListener("mousedown", start, false);
canvas.addEventListener("mousemove", draw, false);
canvas.addEventListener("touchend", stop, false);
canvas.addEventListener("mouseup", stop, false);
canvas.addEventListener("mouseout", stop, false);
function start(event) {
is_drawing = true;
context.beginPath();
context.moveTo(event.clientX - canvas.offsetLeft,
event.clientY - canvas.offsetTop);
event.preventDefault();
}
function draw(event) {
if ( is_drawing ) {
context.lineTo(event.clientX - canvas.offsetLeft,
event.clientY - canvas.offsetTop);
context.strokeStyle = draw_color;
context.lineWidth = draw_width;
context.lineCap = "round";
context.lineJoin = "round";
context.stroke();
}
event.preventDefault();
}
function stop(event) {
if ( is_drawing ) {
context.stroke();
context.closePath();
is_drawing = false;
}
event.preventDefault();
if (event.type != 'mouseout' ) {
restore_array.push(context.getImageData(0, 0, canvas.width, canvas.height));
index += 1;
}
}
function clear_canvas() {
context.fillStyle = start_background_color;
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillRect(0, 0, canvas.width, canvas.height);
restore_array = [];
index = -1;
}
function undo_last() {
if (index <= 0 ) {
clear_canvas();
} else {
index -= 1;
restore_array.pop();
context.putImageData(restore_array[index], 0, 0);
}
}