canvas實現的小球四壁碰撞效果程式碼例項
本章節分享一段程式碼例項,它利用canvas實現了小球在一個封閉區域四壁碰撞效果。
程式碼比較簡單,裡面涉及到了不少關於canvas的小知識點,感興趣的朋友可以做一下參考。
程式碼例項如下:
[HTML] 純文字檢視 複製程式碼<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.softwhy.com/" /> <title>螞蟻部落</title> <style> div { width: 610px; height: 610px; margin: 0px auto; } </style> </head> <body> <div> <canvas id="canvas" width="600" height="600" style="border:1px solid #ccc;"></canvas> </div> <script> var canvas = document.getElementById("canvas"); var context = canvas.getContext("2d"); context.fillStyle = "#0ff"; var ban = { X: 20, Y: 20, H: 1,//水平方向 V: 1,//垂直方向 h: null,//水平的方向增量 v: null,//垂直的方向增量 timer: null, init: function () { var me = this; me.h = me.rFn(); me.v = me.rFn(); me.timer = setInterval(me.move.bind(this), 5); }, newRect: function (x, y) {//重新整理頁面 context.clearRect(0, 0, canvas.width, canvas.height); context.fillRect(x, y, 50, 50); }, move: function () {//移動方塊 //如果碰到左邊 if (this.X == 0) { this.H = -this.H; this.h = this.rFn(); } //如果碰到右邊 if ((this.X + 50) == canvas.width) { this.H = -this.H; this.h = this.rFn(); } //如果碰到上邊 if (this.Y == 0) { this.V = -this.V; this.v = this.rFn(); } //如果碰到下邊 if ((this.Y + 50) == canvas.width) { (this.V = -this.V); this.v = this.rFn(); } this.X += (this.H * this.h); this.Y += (this.V * this.v); (this.X + 50) >= canvas.width && (this.X = canvas.width - 50); this.X <= 0 && (this.X = 0); (this.Y + 50) >= canvas.height && (this.Y = canvas.height - 50); this.Y <= 0 && (this.Y = 0); this.newRect(this.X, this.Y); }, rFn: function () {//隨機生成數字 return Math.floor(Math.random() * 10) + 1; }, } window.onload = function () { ban.init(); } </script> </body> </html>
相關文章
- jquery小球碰撞效果程式碼例項jQuery
- canvas實現的彈力小球效果程式碼例項Canvas
- canvas小球隨機漂浮碰撞程式碼例項Canvas隨機
- canvas實現的隨機生成漂浮小球程式碼例項Canvas隨機
- canvas實現的鋸齒效果程式碼例項Canvas
- canvas實現的鐘表效果程式碼例項Canvas
- canvas實現的驗證碼效果程式碼例項Canvas
- 利用canvas實現的驗證碼效果程式碼例項Canvas
- canvas實現的雪花飄落效果程式碼例項Canvas
- canvas實現的藍色雨滴效果程式碼例項Canvas
- canvas實現煙花燃放效果程式碼例項Canvas
- canvas實現的七巧板效果程式碼例項Canvas
- canvas實現的動態心形效果程式碼例項Canvas
- canvas實現的圓形鐘錶效果程式碼例項Canvas
- canvas實現的簡單畫板效果程式碼例項Canvas
- canvas火焰效果程式碼例項Canvas
- js小球拋物線效果程式碼例項JS
- canvas實現的賽貝爾曲線效果程式碼例項Canvas
- canvas實現文字線性漸變效果程式碼例項Canvas
- canvas實現的刮刮樂程式碼例項Canvas
- canvas實現的旋轉的太極圖效果程式碼例項Canvas
- canvas字母雨效果程式碼例項Canvas
- canvas載入效果程式碼例項Canvas
- canvas擺動效果程式碼例項Canvas
- canvas實現的美猴王程式碼例項Canvas
- canvas實現點選產生放射性效果程式碼例項Canvas
- canvas水位進度效果程式碼例項Canvas
- canvas原型鐘錶效果程式碼例項Canvas原型
- canvas氣泡上浮效果程式碼例項Canvas
- canvas田字格效果程式碼例項Canvas
- canvas繪製圓環效果程式碼例項Canvas
- canvas螞蟻線效果程式碼例項Canvas
- canvas實現的變幻線程式碼例項Canvas線程
- canvas實現的多邊形程式碼例項Canvas
- canvas實現的千輪眼程式碼例項Canvas
- js小球重力和碰撞效果JS
- canvas小球碰壁效果Canvas
- jquery實現的選項卡效果例項程式碼jQuery