-
Notifications
You must be signed in to change notification settings - Fork 2
/
mouse-draw-polyline.html
80 lines (73 loc) · 2.19 KB
/
mouse-draw-polyline.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>SVG使用鼠标点击绘制折线效果</title>
</head>
<body>
<div id="box">
<svg id="svg" xmlns="http://www.w3.org/2000/svg" width="600" height="600" style="border: 1px solid #000"></svg>
</div>
<script>
window.onload = () => {
var ming = 'http://www.w3.org/2000/svg'
var oSvg = document.getElementById('svg')
var oPolyLine = null
var pointsNum = ''
var box = document.getElementById('box')
box.appendChild(createTag('svg', {'xmlns': ming}))
oSvg.onmousedown = event => {
var x = event.clientX - box.offsetLeft
var y = event.clientY - box.offsetTop
if(!oPolyLine){
oPolyLine = createTag('polyline', {
'fill': 'none',
'stroke': 'red',
'stroke-width': 2
})
oSvg.appendChild(oPolyLine)
}
if(pointsNum == ''){
pointsNum = `${x},${y}`
}else{
pointsNum += `,${x},${y}`
}
oPolyLine.setAttribute('points', pointsNum)
var oCircle = createTag('circle', {
'cx': x,
'cy': y,
'r': 5,
'fill': 'white',
'stroke': 'red',
'stroke-width': 3
})
oSvg.appendChild(oCircle)
if(event.button == 2){
oSvg.onmousemove = null
oSvg.oncontextmenu = () => {
oSvg.onmousemove = null
return false
}
}else{
oSvg.onmousemove = event => {
if(oPolyLine){
let x = event.clientX - box.offsetLeft
let y = event.clientY - box.offsetTop
oPolyLine.setAttribute('points', `${pointsNum},${x},${y}`)
}
}
}
}
function createTag(tagName, tagAttr){
var tag = document.createElementNS(ming, tagName)
for(let attr in tagAttr){
tag.setAttribute(attr, tagAttr[attr])
}
return tag
}
}
</script>
</body>
</html>