canvas绘制碰撞球动画
碰撞球動(dòng)畫
畫一個(gè)簡單的球
通過選擇器獲取畫布。
var canvas = document.getElementById('canvas');或var canvas = document.querySelector('#canvas')
獲取屏幕寬高,設(shè)置畫布寬高為屏幕寬高,背景色。當(dāng)瀏覽器寬高變化時(shí)重新給canvas元素設(shè)置寬高。
解決方法:
出現(xiàn)滾動(dòng)條是因?yàn)閏anvas是行內(nèi)元素(display:inline-block;),行內(nèi)元素有行內(nèi)行間距,故當(dāng)你設(shè)置畫布寬高為屏幕寬高,滾出滾動(dòng)條那部分即為行間距。既然是行內(nèi)元素引起的,那我就將元素設(shè)置為塊級元素。同時(shí)去除默認(rèn)邊距。
*{margin: 0;padding: 0;}#canvas{background-color: red;display: block;}給函數(shù)添加reSize方法,當(dāng)改變窗口大小時(shí),給畫布重新設(shè)置大小。
var w, h; var canvas = document.querySelector('canvas'); ~~function setSize() {window.onresize = arguments.callee;w = window.innerWidth;h = window.innerHeight;canvas.width = w;canvas.height = h;}();//立即執(zhí)行函數(shù)寫法之一,//還有(function(){}());//或(function(){})();獲取畫布可畫區(qū)域(getContext)
設(shè)置是2d效果還是3d效果。
var canCon = canvas.getContext('2d');
設(shè)置用什么筆和筆的顏色。
canCon.fillStyle = 'red';
構(gòu)思圖形。
提筆。(beginPath)
畫什么形狀,圖形的位置,大小。
canCon.arc(300,100,50,0,2*Math.PI)
開始畫。
確定空心還是實(shí)心(stroke或fill)。
還是繪制文字。(fillText,strokeText)
canCon.fill()
至此一個(gè)閃動(dòng)的滾動(dòng)條出現(xiàn)。
要出現(xiàn)很多球群魔亂舞現(xiàn)象,需要構(gòu)造一個(gè)球的生成函數(shù),里面包括初始化值,畫球,還有球的移動(dòng)。
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>*{margin: 0;padding: 0;}canvas{background-color: black;display: block;}</style> </head> <body><canvas></canvas> </body> </html> <script>var canvas = document.querySelector('canvas');var w,h;var aBubble = [];~~function(){window.onresize = arguments.callee;w = window.innerWidth;h = window.innerHeight;canvas.width = w;canvas.height = h;}();var canCon = canvas.getContext('2d');function Bubble(){};Bubble.prototype = {init:function(){this.r = random(4,6);this.x = random(this.r,w);this.y = random(this.r,h);this.color = randomColor();this.vx = random(-2,2);this.vy = random(-1,1);},draw:function(){canCon.beginPath();canCon.fillStyle = this.color;canCon.arc(this.x,this.y,this.r,0,Math.PI * 2);canCon.fill();},move:function(){this.x += this.vx;this.y += this.vy;if(this.x < this.r || this.x + this.r > w){this.vx = -this.vx;}if(this.y < this.r || this.y + this.r > h){this.vy = -this.vy;}this.draw();}}function create(num){for(var i = 0; i < num; i++){var bubble = new Bubble();bubble.init();bubble.draw();aBubble.push(bubble);}}create(999);setInterval(function(){canCon.clearRect(0,0,w,h); //必須有這一句,不然賤淚橫生for(var item of aBubble){item.move();}},1000/60);// 隨機(jī)數(shù)function random(min, max){return Math.floor(Math.random() * (max - min) + min);}// 隨機(jī)顏色生成器function randomColor(){var r,g,b,a;r = random(0,255);g = random(0,255);b = random(0,255);a = Math.random();return `rgba(${r},${g},$,${a})`;} </script>知識點(diǎn):
總結(jié)
以上是生活随笔為你收集整理的canvas绘制碰撞球动画的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 碰撞的小球
- 下一篇: Google Glass众叛亲离?