-
Notifications
You must be signed in to change notification settings - Fork 0
/
canvas.html
63 lines (58 loc) · 1.5 KB
/
canvas.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
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.canvas-box {
position: relative;
}
canvas {
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2)
}
</style>
<div class="canvas-box">
<canvas id="cvs" width="500" height="400">不支持canvas</canvas>
</div>
<script>
var cvs = document.getElementById('cvs');
var ctx = cvs.getContext('2d');
// 封装绘制的图形
function draw() {
ctx.fillStyle = '#000';
ctx.beginPath();
ctx.moveTo(100, 100);
ctx.bezierCurveTo(110, 110, 199, 278, 300, 379);
ctx.lineTo(400, 100)
ctx.closePath();
}
function circle() {
ctx.fillStyle = '#000';
ctx.beginPath();
ctx.arc(100, 200, 50, 0, Math.PI * 2)
ctx.closePath();
}
// 初始化绘制图形
draw();
ctx.fill()
circle();
ctx.fill()
var fns = [draw, circle];
// 监听鼠标事件
cvs.onmousemove = function (e) {
// 得到鼠标的坐标
var x = e.pageX,
y = e.pageY;
ctx.clearRect(0, 0, 400, 300)
// 遍历绘制图形
for (var i = fns.length; i--;) {
fns[i]();
// 每绘制一个图形就判断一次当前鼠标的坐标是否在这个图形上,然后进行自定义操作
if (ctx.isPointInPath(x, y)) {
ctx.fillStyle = "#f00"
} else {
ctx.fillStyle = "#000"
}
ctx.fill()
}
}
</script>