iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 13
0
Modern Web

菜雞用Canvas/Pixi動動動動動起來系列 第 13

【Day13】Canvas-進階動畫"彈跳球"

彈跳球

回想多年以前的鐵人賽,我好像也做過彈跳球的動畫CSS彈跳球,而今天做的跟之前的差別在哪呢?就是今天的能用程式控制動畫,包含觸發的時間跟球速等等。所以今天來做個更進階的加上球速的彈跳球吧~

預設資料

start:true,//是否開始丟球
balling:false,//是否丟球中
ctx:null,
posX:25,//一開始球的X座標
posY:25,//一開始球的Y座標
radius:25,//球半徑
color:"blue",//球顏色
vx:2,//預設球的X軸速度
vy:2//預設球的Y軸速度

畫球

drawBall(){
 this.ctx.beginPath()
 this.ctx.arc(this.posX,this.posY,this.radius,0,Math.PI*2,true)
 this.ctx.fillStyle=this.color
 this.ctx.fill()
},

丟起來!

在這邊我犯了一個很蠢的錯誤,一開始我的球會一直超出畫布一點點,一直在想為什麼,後來才想到posXposY是球的圓心位置,所以圓心可以到的Y軸最底位置其實是畫布的高 - 球的半徑,自己都把前幾天自己寫的圓的畫法忘記了QQ。球的畫法看這裡

draw(){
    //產生動畫,也就是讓球丟下來
    this.start=false
    this.balling=true
    this.ctx.clearRect(0,0,600,300)
    this.drawBall(this.ctx)
      
    //設定Y軸速度隨著時間變長速度愈來愈少
    this.vx*=.99
    //設定畫布X軸邊界,讓球的位置到畫布邊界時擋住
    if(this.posX+this.vx>600-this.radius || this.posX+this.vx<this.radius){
      this.vx=-(this.vx)
    }
    this.posX+=this.vx
      
    //設定Y軸速度隨著時間變長速度愈來愈少
    this.vy*=.99
    this.vy+=.25
    //設定畫布Y軸邊界,讓球的位置到畫布邊界時擋住
    if(this.posY+this.vy>300-this.radius || this.posY+this.vy<this.radius){
      this.vy=-(this.vy)
    }

    this.posY+=this.vy
    raf=window.requestAnimationFrame(this.draw)
   }

小小範例

codepen範例連結
成果畫面:

~如有疑問或是錯誤,歡迎不吝指教~

參考來源
[1]https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Advanced_animations
[2]https://www.w3school.com.cn/tags/html_ref_canvas.asp
[3]https://www.runoob.com/w3cnote/html5-canvas-intro.html
[4]http://caibaojian.com/canvas-draw-circle-line.html


上一篇
【Day12】Canvas-基礎動畫"繞圈圈"
下一篇
【Day14】Canvas-進階動畫"繞橢圓"
系列文
菜雞用Canvas/Pixi動動動動動起來30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言