當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
基于JS和Canvas的小球碰撞动画演示
生活随笔
收集整理的這篇文章主要介紹了
基于JS和Canvas的小球碰撞动画演示
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
效果:
1010代碼:
<!DOCTYPE html> <html><head><meta charset="UTF-8"><title></title><style type="text/css">#myCanvas{border: 1px solid black;margin: 20px auto;display:block;}</style></head><body><!--canvas:"畫布",使用來繪制圖形的,最終以圖片的形式顯示在瀏覽器上,默認寬高300/150--><canvas id="myCanvas" width="600" height="600">當前瀏覽器不支持canvas---不兼容</canvas></body><script type="text/javascript"> // 在JS當中,處理canvas繪制過程 // 1.獲取畫布對象var canvas=document.getElementById("myCanvas"); // 注意:在canvas中不使用css樣式設置寬高,canvas繪制的圖像會發生形變; // 可以使用屬性設置; // canvas.width=600//獲取繪制環境的上下文---canvas的'畫筆'var pencil=canvas.getContext("2d");function random(m,n){return Math.floor(Math.random()*(n-m+1)+m);}//通過面向對象的思想,創建小球,以及調用小球移動的方法function Ball(){//設置屬性//隨機小球的半徑this.r = random(5,10);//隨機小球的顏色this.color = "rgb("+random(0,255)+","+random(0,255)+","+random(0,255)+")";//隨機小球圓心x,圓心ythis.x = random(this.r,canvas.width-this.r);//保證小球不出去this.y = random(this.r,canvas.height-this.r);//隨機速度(控制移動方向) // 水平方向上的速度 一半幾率 random(0,1) ? 1:-1 (random(1,10) >= 5 ? 1 : -1)this.speedX = random(2,6)*(random(0,1)?1:-1);//垂直方向上的速度this.speedY = random(2,6)*(random(0,1)?1:-1);}//原型中的寫小球移動的方法Ball.prototype.move = function(){this.x += this.speedX;this.y += this.speedY;//小球碰撞四個邊界反彈//左邊界if(this.x <= this.r){this.x = this.r;//反彈this.speedX *= -1;}//右邊界if(this.x >= canvas.width - this.r){this.x =canvas.width - this.r ;//反彈this.speedX *= -1;}//上邊界if(this.y <= this.r){this.y = this.r;//反彈this.speedY *= -1;}//下邊界if(this.y >= canvas.height- this.r){this.y =canvas.height - this.r ;//反彈this.speedY *= -1; }}//繪制小球的方法Ball.prototype.draw = function(){//開始繪制pencil.beginPath();pencil.arc(this.x,this.y,this.r,0,Math.PI*2,false); // 填充pencil.fillStyle = this.color;pencil.fill();}var balls = [];//存儲所有的小球對象//創建對象for(var i = 0;i < 100;i++){var ball = new Ball();balls.push(ball);}pencil.shadowColor = "lightcyan";pencil.shadowBlur = 30;//讓小球移動起來setInterval(function(){//每次小球重新繪制和移動移動之前,清空畫布中的內容pencil.clearRect(0,0,canvas.width,canvas.height);pencil.beginPath();pencil.fillStyle = "black";pencil.fillRect(0,0,canvas.width,canvas.height);for(var i=0;i<balls.length;i++){balls[i].draw();//繪制小球balls[i].move();//移動小球}},20)// 創建一個小球 // var ball = new Ball(); // setInterval(function(){ // pencil.clearRect(0,0,canvas.width,canvas.height); // ball.draw(); // ball.move(); // },10);</script> </html>?
總結
以上是生活随笔為你收集整理的基于JS和Canvas的小球碰撞动画演示的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ctfmon.exe
- 下一篇: IT技能图谱(图谱+干货)