-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
82 lines (63 loc) · 2.01 KB
/
script.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
window.onload = function () {
// Definitions
var canvas = document.getElementById("paint-canvas");
var context = canvas.getContext("2d");
var boundings = canvas.getBoundingClientRect();
var range = document.getElementById("brush").value;
// Specifications
var mouseX = 0;
var mouseY = 0;
var isDrawing = false;
context.strokeStyle = 'black'; // initial brush color
//Handle brush size
var brush = document.getElementById('brush');
brush.addEventListener('input', function(brush){
context.lineWidth = brush.target.value;
});
// Handle Colors
var colors = document.getElementsByClassName('colors')[0];
colors.addEventListener('click', function(event) {
context.strokeStyle = event.target.value || 'black';
});
// Mouse Down Event
canvas.addEventListener('mousedown', function(event) {
setMouseCoordinates(event);
isDrawing = true;
// Start Drawing
context.beginPath();
context.moveTo(mouseX, mouseY);
});
// Mouse Move Event
canvas.addEventListener('mousemove', function(event) {
setMouseCoordinates(event);
if(isDrawing){
context.lineTo(mouseX, mouseY);
context.stroke();
}
});
// Mouse Up Event
canvas.addEventListener('mouseup', function(event) {
setMouseCoordinates(event);
isDrawing = false;
});
// Handle Mouse Coordinates
function setMouseCoordinates(event) {
mouseX = event.clientX - boundings.left;
mouseY = event.clientY - boundings.top;
}
// Handle Clear Button
var clearButton = document.getElementById('clear');
clearButton.addEventListener('click', function() {
context.clearRect(0, 0, canvas.width, canvas.height);
});
// Handle Save Button
var saveButton = document.getElementById('save');
saveButton.addEventListener('click', function() {
var imageName = prompt('Please enter image name');
var canvasDataURL = canvas.toDataURL();
var a = document.createElement('a');
a.href = canvasDataURL;
a.download = imageName || 'drawing';
a.click();
});
};