-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdraw2.js
More file actions
72 lines (58 loc) · 2.02 KB
/
draw2.js
File metadata and controls
72 lines (58 loc) · 2.02 KB
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
document.addEventListener('DOMContentLoaded', () => {
// state
let draw = false;
// elements
let points = [];
let lines = [];
let svg = null;
function render() {
// create the selection area
svg = d3.select('#draw')
.attr('height', window.innerHeight)
.attr('width', window.innerWidth);
svg.on('mousedown', function() {
draw = true;
const coords = d3.mouse(this);
draw_point(coords[0], coords[1], false);
});
svg.on('mouseup', () =>{
draw = false;
});
svg.on('mousemove', function() {
if (!draw)
return;
const coords = d3.mouse(this);
draw_point(coords[0], coords[1], true);
});
document.querySelector('#erase').onclick = () => {
for (let i = 0; i < points.length; i++)
points[i].remove();
for (let i = 0; i < lines.length; i++)
lines[i].remove();
points = [];
lines = [];
}
}
function draw_point(x, y, connect) {
const color = document.querySelector('#color-picker').value;
const thickness = document.querySelector('#thickness-picker').value;
if (connect) {
const last_point = points[points.length - 1];
const line = svg.append('line')
.attr('x1', last_point.attr('cx'))
.attr('y1', last_point.attr('cy'))
.attr('x2', x)
.attr('y2', y)
.attr('stroke-width', thickness * 2)
.style('stroke', color);
lines.push(line);
}
const point = svg.append('circle')
.attr('cx', x)
.attr('cy', y)
.attr('r', thickness)
.style('fill', color);
points.push(point);
}
render();
});