ZhangYang's Blog

【实战】Canvas画板

MDN Canvas

https://developer.mozilla.org/zh-CN/docs/Web/API/Canvas_API/Tutorial

代码实现

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
<!DOCTYPE html>
<html lang="zh-Hans">
<head>
<meta charset="UTF-8">
<title>Canvas</title>
<style>
#canvas{
background-color: green;
display: block;
}
body{
margin:0;
}
#eraser{
position: fixed;
bottom:10px;
left:0;
}
</style>
</head>
<body>
<canvas id="canvas" width=400 height=400></canvas>
<button id="eraser">橡皮擦</button>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
initWidthAndHeight()
window.onresize = function() {
initWidthAndHeight()
}
var using = false // 是否在使用画板
var useEraser = false // 是否使用橡皮擦
var firstPoint;
var lastPoint;
canvas.onmousedown = function(event) {
var x = event.clientX
var y = event.clientY
using = true
if (useEraser) {
ctx.clearRect(x - 5, y - 5, 10, 10);
} else {
firstPoint = {
x: x,
y: y
}
drawArc(x, y)
}
}
canvas.onmousemove = function(event) {
var x = event.clientX
var y = event.clientY
if(using){
if(useEraser){
ctx.clearRect(x - 5, y - 5, 10, 10);
}else{
lastPoint = {
x: x,
y: y
}
drawLine(firstPoint.x, firstPoint.y, lastPoint.x, lastPoint.y)
firstPoint = lastPoint
drawArc(x, y)
}
}
}
canvas.onmouseup = function() {
using = false
}
eraser.onclick = function() {
useEraser = !useEraser
}
function drawArc(x, y) {
ctx.beginPath();
ctx.arc(x, y, 5, 0, Math.PI * 2)
ctx.fill()
}
function drawLine(x1, y1, x2, y2) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
function initWidthAndHeight() {
var width = document.documentElement.clientWidth
var height = document.documentElement.clientHeight
canvas.width = width
canvas.height = height
}
</script>
</body>
</html>