标签:验证 begin 阅读 event 网上 canvas 响应 etc 字母
window.onkeydown = function(){ alert("Merry Christmas!"); };
window.onkeydown = function(eve){ alert(eve.keyCode); };
window.onkeydown = function(eve){ alert("所按键对应的键码是: " + eve.keyCode); };
window.onkeydown = function(eve){ if(eve.keyCode == 38 || eve.keyCode == 87){ alert("上"); }else if(eve.keyCode == 40 || eve.keyCode == 83){ alert("下"); }else if(eve.keyCode == 37 || eve.keyCode == 65){ alert("左"); }else if(eve.keyCode == 39 || eve.keyCode == 68){ alert("右"); } };
window.onkeydown = function(eve){ switch(eve.keyCode){ case 38: case 87: alert("上"); break; case 40: case 83: alert("下"); break; case 37: case 65: alert("左"); break; case 39: case 68: alert("右"); } };
function drawTank(x,y){ var myCanvas = document.getElementById(‘floor‘); var cxt = myCanvas.getContext(‘2d‘); cxt.fillStyle = "#542174"; cxt.fillRect(x,y,20,65); cxt.fillRect(x+70,y,20,65); cxt.fillRect(x+23,y+10,44,50); cxt.fillStyle = "#FCB827"; cxt.beginPath(); cxt.arc(x+45,y+35,16,0,2*Math.PI,false); cxt.closePath(); cxt.fill(); cxt.strokeStyle = "#FCB827"; cxt.lineWidth = "8.0"; cxt.moveTo(x+45,y+35); cxt.lineTo(x+45,y-25); cxt.stroke(); }
drawTank(150,200); //以(150,200)的点为坦克的左上角(左边履带的左上角)造一个坦克
var myCanvas = document.getElementById(‘floor‘); var cxt = myCanvas.getContext(‘2d‘); cxt.fillStyle = "orange"; cxt.fillRect(50,50,300,80);
得到:
cxt.clearRect(0,0,800,500);
//封装一个获取绘图环境的函数 function getCxt(){ var myCanvas = document.getElementById(‘floor‘), myContext = myCanvas.getContext(‘2d‘); return myContext; } //封装一个画坦克的函数,传两个参数x,y,分别代表左上角的横纵坐标 function drawTank(x,y){ var cxt = getCxt(); cxt.fillStyle = "#542174"; cxt.fillRect(x,y,20,65); cxt.fillRect(x+70,y,20,65); cxt.fillRect(x+23,y+10,44,50); cxt.fillStyle = "#FCB827"; cxt.beginPath(); cxt.arc(x+45,y+35,16,0,2*Math.PI,false); cxt.closePath(); cxt.fill(); cxt.strokeStyle = "#FCB827"; cxt.lineWidth = "8.0"; cxt.moveTo(x+45,y+35); cxt.lineTo(x+45,y-25); cxt.stroke(); } //初始化一个对象myTank,用来存储一些属性和方法,避免污染全局空间 var myTank = {}; myTank.x = 350; myTank.y = 400; myTank.step = 3; //设置步长,步长越大那么坦克运动的速度越快 //先画一个坦克出来 drawTank(myTank.x,myTank.y); //封装一个更新战场的函数 function updateFloor(){ var cxt = getCxt(); cxt.clearRect(0,0,800,500); //更新之前先清除画布 drawTank(myTank.x,myTank.y); //清除完之后重新造坦克,坦克要移动就必须实时地根据坐标重新来造 } //设置一个间歇调用的函数,每隔100ms更新一下战场 setInterval(function(){ updateFloor(); },100); //响应玩家的操作指令 window.onkeydown = function(eve){ switch(eve.keyCode){ case 38: case 87: myTank.y -= myTank.step; //Y坐标减小向上移动 break; case 40: case 83: myTank.y += myTank.step; //Y坐标增加向下移动 break; case 37: case 65: myTank.x -= myTank.step; //X坐标减小向左移动 break; case 39: case 68: myTank.x += myTank.step; //X坐标增加向右移动 } };
标签:验证 begin 阅读 event 网上 canvas 响应 etc 字母
原文地址:http://www.cnblogs.com/zhouhuan/p/H5_tankgame2.html