-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathHTML5 - Moving a rectangle.html
More file actions
63 lines (63 loc) · 1.64 KB
/
HTML5 - Moving a rectangle.html
File metadata and controls
63 lines (63 loc) · 1.64 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
<!DOCTYPE = html>
<html><body>
<canvas id="myCanvas" width="320" height="240" style="border:1px solid #d3d3d3;">
Use different browser.
</canvas>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var message="Use cursor keys to move rectangle.";
var rx=c.width/2;
var ry=c.height/2;
var rw=16;
var rh=16;
var moveLeft=false;
var moveRight=false;
var moveUp=false;
var moveDown=false;
gameloop=setInterval(doGameLoop,16);
window.addEventListener("keydown",kd,true);
window.addEventListener("keyup",ku,true);
function doGameLoop(){
ctx.clearRect(0,0,c.width,c.height);
ctx.fillText(message,10,10);
ctx.fillRect(rx,ry,rw,rh);
updateplayer();
}
// Key down function.
function kd(evt){
if(evt.keyCode==37) moveLeft=true;
if(evt.keyCode==39) moveRight=true;
if(evt.keyCode==38) moveUp=true;
if(evt.keyCode==40) moveDown=true;
}
// Key up function
function ku(evt){
if(evt.keyCode==37) moveLeft=false;
if(evt.keyCode==39) moveRight=false;
if(evt.keyCode==38) moveUp=false;
if(evt.keyCode==40) moveDown=false;
}
function updateplayer(){
if(moveLeft==true){
if(rx>0){
rx--;
}
}
if(moveRight==true){
if(rx<(c.width-rw)){
rx++;
}
}
if(moveUp==true){
if(ry>0){
ry--;
}
}
if(moveDown==true){
if(ry<(c.height-rh)){
ry++;
}
}
}
</script></body></html>