游戏二: 随处移动的Ball

来源:互联网 发布:软件总体技术方案 编辑:程序博客网 时间:2024/04/26 04:14

首先, html 提供了2个类似 timer 事件的接口:

setTImeout()                   // 只执行一次

setInterval( 函数, 间隔)  // 其中 间隔 : 1000 表示 1秒 , 反复执行

.js file

// box & ballvar boxx = 20;var boxy = 30;var boxwidth = 350;var boxheight = 250;var ballrad = 10;var boxboundx = boxwidth + boxx - ballrad ; //右边界var boxboundy = boxheight + boxy - 2*ballrad ;//下边界var inboxboundx = boxx + ballrad;//左边界var inboxboundy = boxy + 2*ballrad;//上边界var ballx = 50;var bally = 60;var ctx ;var ballvx = 4;//初始水平速度var ballvy = 8;//初始垂直速度//初始化function init(){ctx = document.getElementById("canvas").getContext("2d");ctx.linewith = ballrad;ctx.fillStyle = "rgb(200, 0, 50)";moveball();setInterval(moveball,100);}//移动function moveball(){ctx.clearRect(boxx,boxy,boxwidth,boxheight);moveandcheck();ctx.beginPath();ctx.arc(ballx,bally,ballrad,0,Math.PI*2,true);ctx.fill();ctx.strokeRect(boxx,boxy,boxwidth,boxheight);}//确认移动方向function moveandcheck(){var nballx = ballx + ballvx ;//新坐标 xvar nbally = bally + ballvy ;//新坐标 yif (nballx > boxboundx){ballvx = -ballvx ;nballx = boxboundx ;//如果达到右边界,就象左}if (nballx < inboxboundx){ballvx = -ballvx ;nballx = inboxboundx ;//如果达到左边界,就象左}if (nbally > boxboundy) {ballvy = -ballvy ;//下边界nablly = boxboundy ;}if (nbally < inboxboundy) {ballvy = -ballvy ;//下边界nablly = inboxboundy ;}ballx = nballx ;bally = nbally;}//提交,改变速度function change(){ballvx = Number( f.hv.value) ;ballvy = Number( f.vv.value );return false ;}


.html file

<!doctype html><html><head><title>Bouncing Ball with inputs</title><script src = "ball.js" type = "text/javascript"></script><link rel = "stylesheet" href = "ball.css" type = "text/css" /></head><body onLoad = "init()"><canvas width = "400" height = "300" id = "canvas" >Your browser doesn't support HTML5.</canvas><br /><form name = "f" id = "f" onSubmit = "return change()">Horizontal velocity <input type = "number" id = "hv" name = "hv" value = "4" min = "-10" max = "10"/><br />Vertial velocity <input type = "number" name = "vv" id = "vv" value = "8" min = "-10" max = "10" /> <input type = "submit" value = "Change" /></form></body></html>


. css file

#hv : valid {background : green ;}input : invalid {background : red ;}form {width : 330 px ;margin : 20 px ;background-color : brown ;padding : 20 px ;}