-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCode5_test_draw.html
84 lines (73 loc) · 2.05 KB
/
Code5_test_draw.html
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
<!DOCTYPE html>
<html>
<head>
<title>Scribbler</title>
<style type="text/css">
canvas {
border: 1px solid black;
background-color: white;
cursor: crosshair;
}
</style>
</head>
<body>
<canvas id="canvas" width="1500" height="1500"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var isDrawing = false;
var points = [];
var lines = [];
canvas.addEventListener("mousedown", function(e) {
isDrawing = true;
points.push({x: e.clientX, y: e.clientY});
});
canvas.addEventListener("mousemove", function(e) {
if (!isDrawing) return;
// Draw current line
ctx.lineWidth = 1;
ctx.lineCap = "round";
ctx.strokeStyle = "black";
ctx.beginPath();
ctx.moveTo(points[points.length - 1].x, points[points.length - 1].y);
ctx.lineTo(e.clientX, e.clientY);
ctx.stroke();
// Add current point
points.push({x: e.clientX, y: e.clientY});
});
canvas.addEventListener("mouseup", function(e) {
isDrawing = false;
// Record line
lines.push(points);
points = [];
// Draw random lines near current point
var radius = 100;
var numLines = 20;
var currentPoint = {x: e.clientX, y: e.clientY};
var nearbyPoints = [];
// Find nearby points from previous lines
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
for (var j = 0; j < line.length; j++) {
var distance = Math.sqrt(Math.pow(line[j].x - currentPoint.x, 2) + Math.pow(line[j].y - currentPoint.y, 2));
if (distance <= radius) {
nearbyPoints.push(line[j]);
}
}
}
// Draw random lines
ctx.lineWidth = 1;
ctx.lineCap = "round";
ctx.strokeStyle = "black";
for (var i = 0; i < numLines; i++) {
var start = nearbyPoints[Math.floor(Math.random() * nearbyPoints.length)];
var end = currentPoint;
ctx.beginPath();
ctx.moveTo(start.x, start.y);
ctx.lineTo(end.x, end.y);
ctx.stroke();
}
});
</script>
</body>
</html>