index.html
2.61 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题</title>
<style>
.xnCanvas{
width: 1024px;
height: 768px;
border: 1px solid #dcdcdc;
}
</style>
</head>
<body>
<h1>HTML Canvas Event Demo - By Gloomy Fish</h1>
<pre>Press W, A, S, D keys to move</pre>
<div class="xn-canvas">
<canvas id="xnCanvas" tabindex="0" width="1024" height="768"></canvas>
</div>
<script type="text/javascript">
var canvasData=[
[{x:20,y:20},{x:120,y:20},{x:120,y:120},{x:20,y:120}],
[{x:120,y:120},{x:120,y:220},{x:220,y:220},{x:220,y:120}],
[{x:330,y:320},{x:600,y:800},{x:400,y:800},{x:220,y:120},{x:800,y:60}]
];
var setMap=function(sample,data,state,loc){
this.state=state;
sample.beginPath();
for(var j=0;j<data.length;j++){
if(j==0){
sample.moveTo(data[j].x,data[j].y);
}else{
sample.lineTo(data[j].x,data[j].y);
}
}
sample.closePath();
//填充
var position=false;
if(loc){
position=sample.isPointInPath(loc.x,loc.y);
}
if(this.state || position){
sample.fillStyle="#000000";
sample.strokeStyle="#ff0000";
}else{
sample.fillStyle="#ffffff";
sample.strokeStyle="#ff0000";
}
sample.stroke();
sample.fill();
};
function draw(loc){
var canvas = document.getElementById('xnCanvas');
if(canvas.getContext) {
var sample = canvas.getContext('2d');
for(var i = 0; i < canvasData.length; i++) {
var state=false;
/* if(2 ==(i+1)){
state=true;
}*/
var c = new setMap(sample,canvasData[i],state,loc);
}
}
}
function getPointOnCanvas(canvas, x, y) {
var bbox = canvas.getBoundingClientRect();
return { x: x - bbox.left * (canvas.width / bbox.width),
y: y - bbox.top * (canvas.height / bbox.height)
};
}
function doMouseDown(event) {
var x = event.pageX;
var y = event.pageY;
var canvas = event.target;
var loc = getPointOnCanvas(canvas, x, y);
console.log("mouse down at point( x:" + loc.x + ", y:" + loc.y + ")");
draw(loc);
}
function main(){
var canvas = document.getElementById("xnCanvas");
draw();
canvas.addEventListener("mousedown", doMouseDown, false);
}
main();
</script>
</body>
</html>