第四講:使用html5中的canvas標籤畫出一個球在指定區域內的運動
阿新 • • 發佈:2019-02-16
<html> <head> <title>小球在一個區域運動</title> <script src="../js/jscex.jscexRequire.min.js" type="text/javascript"></script> </head> <body> <canvas id="mc" width="900px" height="500px"> </canvas> <script type="text/javascript"> var canvas = document.getElementById('mc'); var cxt = canvas.getContext('2d'); //定義一個小球 var ball = { position : {x : 100,y : 100}, //球的位置 r : 30, //球的半徑 vx : 300, //球在X軸的速度 vy : 200 //球在Y軸的速度 }; var cyc = 10; var somethingAsync = eval(Jscex.compile("async", function () { //結合物理裡面的知識即可 while (true) { cxt.fillStyle = "rgba(0, 0, 0, .1)"; cxt.fillRect(0, 0, canvas.width, canvas.height); cxt.fillStyle = "#FA340A"; cxt.beginPath(); cxt.arc(ball.position.x, ball.position.y, ball.r, 0, Math.PI * 2, true); cxt.closePath(); cxt.fill(); //與左右兩邊碰撞 只需X軸的方向相反即可 if(ball.position.x + ball.r > canvas.width || ball.position.x < ball.r ) ball.vx *= -1; //上下兩邊相撞 只需Y軸的方向相反即可 if(ball.position.y + ball.r > canvas.height || ball.position.y < ball.r ) ball.vy *= -1; //在判斷完成之後 再進行球的移動 ball.position.x += ball.vx * cyc /1000; ball.position.y += ball.vy * cyc /1000; $await(Jscex.Async.sleep(cyc)); } })); somethingAsync().start(); </script> </body> </html>