-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcanvas.html
More file actions
81 lines (72 loc) · 1.95 KB
/
canvas.html
File metadata and controls
81 lines (72 loc) · 1.95 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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>画板</title>
<style>
* {
margin: 0px;
padding: 0px;
box-sizing: border-box
}
#canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="canvas" width="100" height="100"></canvas>
<script>
let canvas = document.getElementById("canvas");
canvas.width = document.documentElement.clientWidth;
canvas.height = document.documentElement.clientHeight;
let ctx = canvas.getContext("2d");
ctx.fillStyle = "black";
ctx.strokeStyle = 'black';
ctx.lineWidth = 8;
ctx.lineCap = "round";
let painting = false;
let last;
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 {
// PC端鼠标按下
canvas.onmousedown = (e) => {
painting = true;
last = [e.clientX, e.clientY];
}
// PC端鼠标按住移动
canvas.onmousemove = (e) => {
if (painting === true) {
drawLine(last[0], last[1], e.clientX, e.clientY);
last = [e.clientX, e.clientY];
}
}
// PC端鼠标松开
canvas.onmouseup = () => {
painting = false;
}
}
// 封装画线方法
function drawLine(x1, y1, x2, y2){
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.stroke();
}
</script>
</body>
</html>