forked from soyaine/JavaScript30
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex-SOYAINE.html
More file actions
109 lines (92 loc) · 2.21 KB
/
Copy pathindex-SOYAINE.html
File metadata and controls
109 lines (92 loc) · 2.21 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML5 Canvas</title>
</head>
<body>
<canvas id="draw" width="800" height="800" style="overflow:auto;"></canvas>
<script>
const canvas = document.querySelector('#draw');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let isDrawing = false;
let lastX = 0;
let lastY = 0;
ctx.lineWidth = 90;
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.strokeStyle = "#f00";
ctx.fillStyle = "#f00";
let hue = 0;
let direction = true;
let x = 0;
let y = 0;
function draw(e) {
if(!isDrawing) return;
// console.log(e.type);
if(e.type == "mousemove"){
x = e.offsetX;
y = e.offsetY;
} else {
// 处理触摸屏操作
x = e.changedTouches[0].clientX;
y = e.changedTouches[0].clientY;
// console.log(e);
}
// 彩虹效果
ctx.strokeStyle = `hsl(${ hue }, 90%, 50%)`;
if(hue >= 360) hue = 0;
hue++;
// 水墨效果
// ctx.strokeStyle = `rgba(0, 0, 0, ${ hue })`;
// if(hue >= 0.7) hue = 0;
// hue += 0.01;
// 控制笔触大小
if(ctx.lineWidth > 120 || ctx.lineWidth < 10) {
direction = !direction;
}
if (direction) {
ctx.lineWidth++;
} else {
ctx.lineWidth--;
}
// 控制绘制路径
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(x, y);
ctx.stroke();
// lastX = x;
// lastY = y;
[lastX, lastY] = [x, y];
// console.log(ctx.lineWidth);
// console.log(x +"-" + e.offsetX);
}
canvas.addEventListener('mousedown', (e) => {
isDrawing = true;
[lastX, lastY] = [e.offsetX, e.offsetY];
});
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', () => isDrawing = false);
canvas.addEventListener('mouseout', () => isDrawing = false);
canvas.addEventListener('touchstart', (e) => {
isDrawing = true;
lastX = e.changedTouches[0].clientX;
lastY = e.changedTouches[0].clientY;
});
canvas.addEventListener('touchmove', draw);
canvas.addEventListener('touchend', () => isDrawing = false);
canvas.addEventListener('touchcancel', () => isDrawing = false);
</script>
<style>
html, body {
margin:0;
overflow: hidden;
}
canvas {
overflow: hidden;
}
</style>
</body>
</html>