# Canvas Animation 01 : Bubble ###### tags: `Animation-Canvas` ## 一 . 概念 ### (一) . 成果圖 : ### (二) . 分析 : 1. 程式的角度分析動畫 : - 每一個點都設計成一個物件,帶有自己的屬性(位置)和方法(更新位置)。 - 而瀏覽器每秒用多次的渲染,依據每個點所在的位置,重新繪圖。 2. 物件設計 : 既然每一個點都要成為一個物件,設計物件的內容。 - 屬性 : 位置、速度、顏色、尺寸(大小)。 - 方法 : 更新位置、重新繪圖。 3. 結論 : - 程式每一次重新更新畫布(清空)。 - 程式每次呼叫每一個點(物件)的方法做更新位置和重新繪圖。 ## 二 . 物件設計 ```javascript= class Circle{ constructor(x, y, radius, dx, dy,color){ this.x=x; this.y=y; this.radius=radius; this.dx=dx; // dx is v of x-direction this.dy=dy; // dy is v of y-direction this.color=color; } draw(){ ctx.beginPath(); ctx.strokeStyle=this.color; ctx.arc(this.x, this.y, this.radius, 0 , 2*Math.PI); ctx.stroke(); } update(){ if((this.x+this.radius) >= window.innerWidth || (this.x-this.radius) <= 0){ this.dx= -this.dx; } if((this.y+this.radius) >= window.innerHeight || (this.y-this.radius) <= 0){ this.dy= -this.dy; } this.x+=this.dx; this.y+=this.dy; this.draw(); } } ``` ### (一) . 建構子 : 決定屬性 ```javascript= constructor(x, y, radius, dx, dy,color){ this.x=x; this.y=y; this.radius=radius; this.dx=dx; // dx is v of x-direction this.dy=dy; // dy is v of y-direction this.color=color; } ``` - 位置 : 代表每次要繪圖的x和y座標。 - 半徑 : 代表圓圈的大小,即尺寸。 - 速度 : 代表下一次位置更新時的移動方向和距離。 - 顏色 : 代表每一個物件的著色。 ### (二) . ```draw()``` : 使用畫筆,依照每個點的屬性繪圖 ```javascript= draw(){ ctx.beginPath(); ctx.strokeStyle=this.color; ctx.arc(this.x, this.y, this.radius, 0 , 2*Math.PI); ctx.stroke(); } ``` - 標準的畫筆使用流程 - 第三行 : 指定物件屬性,指定顏色給畫筆。 - 第四行 : 指定物件屬性,將物件的位置和半徑指定給畫筆。 ### (三) . ```update()``` : 更新物件屬性 ```javascript= update(){ if((this.x+this.radius) >= window.innerWidth || (this.x-this.radius) <= 0){ this.dx= -this.dx; } if((this.y+this.radius) >= window.innerHeight || (this.y-this.radius) <= 0){ this.dy= -this.dy; } this.x+=this.dx; this.y+=this.dy; this.draw(); } ``` - 更新物件屬性 : 模擬『速度』的物理現象。 - 第八行、第九行 : 根據物理公式,$x'=x+v$。 - 第十行 : 更新完位置,重新繪圖。 - 模擬反彈 : 第二行到第五行