簡體   English   中英

使用三角函數對 HTML5 canvas 進行動畫處理,但是如何為 position 這個正方形設置動畫?

[英]Using trigonometry to animate HTML5 canvas, but how to position this square?

有時你希望你能及時回到過去告訴年輕的自己,數學確實很重要。 但我懷疑我當時會聽。 在這個特定的例子中,我最近一直在使用 animation 和 HTML5 canvas 的三角學。

這是一個超級簡單的 animation:它以圓形方式圍繞 canvas 的中心定位一個圓弧。 X 和 Y 位置是根據基本三角函數 sinus 和 cosinus 計算的。 “SohCahToa”。 我想我開始明白了。 但不知何故,我無法弄清楚如何在其中一個三角形邊的中間畫一個正方形。

GIF 顯示問題。

let radius = 200;
let angle = 0;
x = centerX + Math.cos(angle) * radius;

ctx.beginPath();
ctx.fillRect(x/2, centerY, 20, 20);

https://codepen.io/melvinidema/pen/wvKPepa?editors=1010

因此,通過將 canvas 的中心與返工公式相加來繪制圓弧:(co)sinus - 對於 X = Cos,對於 Y = Sin) 角度乘以圓的半徑。

如果我們只取X position(紅線),想畫出圓弧的position的正方形一半。 (所以在紅線中間)我們應該能夠將新計算的 X position 除以 2,對吧? 但如果我這樣做,正方形會神奇地完全畫在圓圈之外。

發生了什么? 為什么它會這樣? 在整個 animation 的紅線中間,我應該使用什么計算來代替 position 的平方?

提前致謝!

您的x定義為:

x = centerX + Math.cos(angle) * radius;

但是當你想除以 2 時,你只需要除Math.cos(angle) * radius ,而centerX是零點,它的立場是這樣的。

所以矩形應該放在:

centerX + Math.cos(angle)/2

另外,我認為如果你減少一半的矩形寬度會更好,並得到:

centerX + Math.cos(angle)/2 - 10

 const canvas = document.querySelector('canvas'); const ctx = canvas.getContext('2d'); let radius = 200; function frame(angle) { const cx = canvas.width / 2, cy = canvas.height / 2, x = Math.cos(angle) * radius, y = Math.sin(angle) * radius; ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.beginPath(); ctx.moveTo(cx, cy); ctx.lineTo(cx+x, cy+y); ctx.lineTo(cx+x, cy); ctx.lineTo(cx, cy); ctx.stroke(); ctx.closePath(); ctx.beginPath(); ctx.arc(cx+x, cy+y, 10, 0, Math.PI*2); ctx.fill(); ctx.fillRect(cx + x/2 - 10, cy - 10, 20, 20); ctx.closePath(); requestAnimationFrame(()=>frame(angle+.03)); } frame(0)
 canvas { display: block; max-height: 100vh; margin: auto; }
 <canvas width="500" height="500"></canvas>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM