-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
83 lines (74 loc) · 2.64 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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>HTML5 Canvas绘制线条入门示例</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<!-- 添加canvas标签,并加上红色边框以便于在页面上查看 -->
<div style="height:100px"></div>
<canvas id="myCanvas" width="400px" height="300px" style="border: 1px solid red;">
您的浏览器不支持canvas标签。
</canvas>
<script type="text/javascript">
//获取Canvas对象(画布)
var canvas = document.getElementById("myCanvas");
//简单地检测当前浏览器是否支持Canvas对象,以免在一些不支持html5的浏览器中提示语法错误
var element = canvas.getContext('2d');
var ctx;
if (canvas.getContext) {
//获取对应的CanvasRenderingContext2D对象(画笔)
ctx = canvas.getContext("2d");
//注意,Canvas的坐标系是:Canvas画布的左上角为原点(0,0),向右为横坐标,向下为纵坐标,单位是像素(px)。
//开始一个新的绘制路径
ctx.beginPath();
//定义直线的起点坐标为(10,10)
ctx.moveTo(0, 0);
//定义直线的终点坐标为(50,10)
ctx.lineTo(100, 100);
ctx.fill();
ctx.lineWidth = 5;
//沿着坐标点顺序的路径绘制直线
ctx.stroke();
//关闭当前的绘制路径
ctx.closePath();
}
//canvas.addEventListener("mousemove", mousemove);
canvas.addEventListener("mousedown", mousedown);
function mousemove(event) {
var start = 0;
var end = 1;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(100, 100);
ctx.lineTo(200, 200);
ctx.stroke();
//鼠标点击canvas,获取的鼠标点击的位置(x,y)
var x = event.clientX - canvas.getBoundingClientRect().left;
var y = event.clientY - canvas.getBoundingClientRect().top;
// draw(x,y);
console.log("x,y", x, y)
console.log(ctx.isPointInPath(x, y));
if (ctx.isPointInPath(x, y)) {
ctx.moveTo(100, 100);
ctx.lineTo(200, 200);
ctx.stroke();
}
}
function mousedown(event) {
//鼠标点击canvas,获取的鼠标点击的位置(x,y)
var x = event.clientX - canvas.getBoundingClientRect().left;
var y = event.clientY - canvas.getBoundingClientRect().top;
// draw(x,y);
console.log("x,y", x, y)
console.log(ctx.isPointInPath(x, y));
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(100, 100);
ctx.lineTo(200, 200);
ctx.stroke();
}
</script>
</body>
</html>