-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCode2_test_draw.html
80 lines (71 loc) · 2.43 KB
/
Code2_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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Line Brush with Random Lines Based on Previous Line</title>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<script>
// 获取画布和画笔
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// 设置笔刷属性
var brushSize = 1;
var brushColor = "#000000";
// 设置随机线属性
var randomLineLength = 10;
var randomLineColor = "#000000";
// 保存上一次绘制的结束点和随机点
var lastEnd = null;
var lastRand = null;
// 监听鼠标事件
canvas.addEventListener("mousedown", startDraw);
canvas.addEventListener("mousemove", draw);
canvas.addEventListener("mouseup", endDraw);
// 开始绘制
function startDraw(e) {
ctx.beginPath();
ctx.moveTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
lastEnd = { x: e.clientX - canvas.offsetLeft, y: e.clientY - canvas.offsetTop };
canvas.addEventListener("mousemove", draw);
}
// 绘制
function draw(e) {
ctx.lineTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
ctx.lineWidth = brushSize;
ctx.strokeStyle = brushColor;
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.stroke();
// 在当前按下的路径中添加随机的连线
if (lastEnd) {
if (!lastRand) {
// 如果上一次没有随机点,则在当前按下的点和上一次结束点之间随机选择一个点
var randX = lastEnd.x + Math.random() * (e.clientX - lastEnd.x);
var randY = lastEnd.y + Math.random() * (e.clientY - lastEnd.y);
lastRand = { x: randX, y: randY };
} else {
// 如果上一次有随机点,则在上一次随机点和当前按下的点之间随机选择一个点
var randX = lastRand.x + Math.random() * (e.clientX - lastRand.x);
var randY = lastRand.y + Math.random() * (e.clientY - lastRand.y);
ctx.beginPath();
ctx.moveTo(lastRand.x, lastRand.y);
ctx.lineTo(randX, randY);
ctx.lineWidth = brushSize/2;
ctx.strokeStyle = randomLineColor;
ctx.stroke();
lastRand = { x: randX, y: randY };
}
}
lastEnd = { x: e.clientX - canvas.offsetLeft, y: e.clientY - canvas.offsetTop };
}
// 结束绘制
function endDraw() {
canvas.removeEventListener("mousemove", draw);
lastEnd = null;
lastRand = null;
}
</script>
</body
</html>