-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
100 lines (87 loc) · 3.08 KB
/
index.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>canvas简单画板</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<!-- 用JavaScript来画线会非常卡顿,会一直创建 DOM 节点,用 canvas 就会快很多
<div id="canvas"></div>
<script>
canvas.onmousemove = (e) => {
console.log(e);
console.log(e.clientX);
let div = document.createElement('div');
div.style.position = 'absolute';
div.style.left = e.clientX + 'px';
div.style.top = e.clientY + 'px';
div.style.width = '6px';
div.style.height = '6px';
div.style.marginLeft = '-3px';
div.style.marginTop = '-3px';
div.style.borderRadius = '50%'
div.style.backgroundColor = 'black'
canvas.appendChild(div);
}
</script> -->
<canvas id="canvas" width="100" height="100"></canvas>
<script>
const canvas = document.getElementById('canvas');
canvas.width = document.documentElement.clientWidth;
canvas.height = document.documentElement.clientHeight;
const ctx = canvas.getContext('2d');
let painting = false;
let last;
ctx.fillStyle = 'black';
ctx.strokeStyle = 'none';
ctx.lineWidth = 10;
ctx.lineCap = 'round';
function drawLine(x1, y1, x2, y2) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
// 判断是否支持手机上的触屏
var isTouchDevice = 'ontouchstart' in document.documentElement;
if (isTouchDevice) {
canvas.ontouchstart = (e) => {
let x = e.touches[0].clientX;
let y = e.touches[0].clientY;
last = [x, y];
}
canvas.ontouchmove = (e) => {
let x = e.touches[0].clientX;
let y = e.touches[0].clientY;
drawLine(last[0], last[1], x, y)
last = [x, y];
}
} else {
ctx.fillStyle = 'black';
canvas.onmousedown = (e) => {
painting = true;
last = [e.clientX, e.clientY]
}
canvas.onmousemove = (e) => {
if (painting === true) {
// // 绘制矩形
// // ctx.fillRect(e.clientX - 3, e.clientY - 3, 6, 6);
// // 绘制圆形
// ctx.beginPath();
// ctx.arc(e.clientX, e.clientY, 3, 0, 2 * Math.PI);
// // stroke描边,fill填充
// ctx.stroke();
// ctx.fill();
drawLine(last[0], last[1], e.clientX, e.clientY)
last = [e.clientX, e.clientY]
}
}
canvas.onmouseup = () => {
painting = false;
}
}
</script>
</body>
</html>