forked from llimllib/refresh-canvas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmouse.html
119 lines (106 loc) · 2.57 KB
/
mouse.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<html>
<head>
<script type="text/javascript" src="jquery-1.2.6.js"></script>
<script type="application/x-javascript">
var x = 75;
var y = 75;
var WIDTH = 300;
var HEIGHT = 300;
var paddlex = WIDTH/2;
var paddledx = WIDTH/75;
var paddlewidth = WIDTH/4;
var dx, dy = 0;
var intervalID = 0;
var canvas, ctx;
var rightDown = false;
var leftDown = false;
var mouser = "deleteme";
var canvasMinX = 0;
var canvasMaxX = 0;
function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
canvasMinX = $("#canvas").offset().left;
canvasMaxX = canvasMinX + $("#canvas").width();
x = 75;
y = 75;
dx = parseFloat($("#dx").val());
dy = parseFloat($("#dy").val());
draw();
}
function startdraw() {
init();
clearInterval(intervalID);
intervalID = setInterval(draw, 20);
}
function abort() {
clearInterval(intervalID);
ctx.clearRect(0,0,300,300);
init();
}
function draw() {
ctx.clearRect(0,0,300,300);
//draw ball
ctx.fillStyle = 'black';
ctx.beginPath();
ctx.arc(x,y,10,0,Math.PI*2,true);
ctx.fill();
px = paddlex - paddlewidth / 2;
ctx.fillRect(px, HEIGHT-10, paddlewidth, HEIGHT);
//update x and y
x += dx;
y += dy;
if (x > WIDTH || x < 0) {
x -= 2*dx;
dx = -dx;
}
if ((y > HEIGHT && x > px && x < px + paddlewidth) || y < 0) {
y -= 2*dy;
dy = -dy;
}
else if (y > HEIGHT) {
//TODO: you lose!
clearInterval(intervalID);
}
if (leftDown)
paddlex -= paddledx;
else if (rightDown)
paddlex += paddledx;
}
function doKeyDown(evt) {
//right is 39 left is 37
if (evt.keyCode == 39) {
rightDown = true;
}
else if (evt.keyCode == 37) {
leftDown = true;
}
}
function doKeyUp(evt) {
if (evt.keyCode == 39) {
rightDown = false;
}
else if (evt.keyCode == 37) {
leftDown = false;
}
}
function mouseMove(evt) {
if (evt.pageX > canvasMinX && evt.pageX < canvasMaxX) {
paddlex = evt.pageX - canvasMinX;
}
}
$(document).keydown(doKeyDown);
$(document).keyup(doKeyUp);
$(document).mousemove(mouseMove);
</script>
</head>
<body onload="init()">
<canvas id="canvas" width="300" height="300" style="border:1px solid;"></canvas>
<br>
<form>
dx: <input type="text" id="dx" size="4" value="1"/>
dy: <input type="text" id="dy" size="4" value="4"/>
<input type="submit" onclick="startdraw(); return false;" value="draw">
<input type="submit" onclick="abort(); return false;" value="clear">
</body>
</html>