Skip to content

Commit efb673e

Browse files
committed
js-8
1 parent 4ba7315 commit efb673e

1 file changed

Lines changed: 89 additions & 0 deletions

File tree

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
4+
<head>
5+
<meta charset="UTF-8">
6+
<title>HTML5 Canvas</title>
7+
</head>
8+
9+
<body>
10+
<canvas id="draw" width="800" height="800"></canvas>
11+
<script>
12+
/* 整体思路:1.获取宽高,确定鼠标事件监听范围
13+
2.初始化画笔的线条填充色和形状、衔接形状、结尾形状
14+
3. 定义初始点、是否要绘画的变量
15+
4. 优化事件:颜色、线条
16+
*/
17+
18+
const canvas = document.querySelector('#draw');
19+
const ctx = canvas.getContext('2d');
20+
21+
// 画板的宽高
22+
canvas.width = window.innerWidth;
23+
canvas.height = window.innerHeight;
24+
25+
// 线条样式
26+
ctx.strokeStyle = '#BADA55' // 填充色
27+
ctx.lineJoin = 'round'; // 两条线段的衔接处
28+
ctx.lineCap = 'round'; // 线段结尾形状
29+
ctx.lineWidth = 100; //线条宽度
30+
31+
32+
let isDrawing = false;
33+
let lastX = 0; //起点初始值
34+
let lastY = 0;
35+
let hue = 0; //h(hue)s(Saturation)l(light)色相变量
36+
let direction = false // lineWidth线条粗细变量
37+
38+
39+
function draw(e) {
40+
if (!isDrawing) return;
41+
[lastX, lastY] = [e.offsetX, e.offsetY]
42+
ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`
43+
ctx.beginPath()
44+
ctx.moveTo(lastX, lastY)
45+
ctx.lineTo(e.offsetX, e.offsetY)
46+
// console.log('e.offsetX, e.offsetY', e.offsetX, e.offsetY)
47+
ctx.stroke()
48+
49+
hue++;
50+
if (hue >= 360) {
51+
hue = 0
52+
}
53+
if (ctx.lineWidth >= 100 || ctx.lineWidth <= 0) {
54+
direction = !direction;
55+
}
56+
57+
if (direction) {
58+
ctx.lineWidth++;
59+
} else {
60+
ctx.lineWidth--;
61+
}
62+
}
63+
64+
// 监听mouseDown事件,鼠标按下
65+
canvas.addEventListener('mousedown', e => {
66+
isDrawing = true;
67+
// console.log(e)
68+
})
69+
70+
// 监听mouseMove事件,鼠标移动,没有区分按下与否
71+
canvas.addEventListener('mousemove', draw)
72+
73+
// 监听mouseUp事件,按钮放开
74+
canvas.addEventListener('mouseup', () => isDrawing = false)
75+
76+
// 监听mouseOut事件,移出画板
77+
canvas.addEventListener('mouseout', () => isDrawing = false)
78+
</script>
79+
80+
<style>
81+
html,
82+
body {
83+
margin: 0;
84+
}
85+
</style>
86+
87+
</body>
88+
89+
</html>

0 commit comments

Comments
 (0)