for (let angle = 0; angle < Math.PI * 2; angle += 0.1) { console.log(Math.sin(angle)); }这段代码可以帮助你理解正弦波是如何生成的。接下来,我们就用这个波形来做点动画效果吧!
window.onload = () => { const canvas = document.getElementById('canvas'); const context = canvas.getContext('2d'); const ball = new Ball(); let angle = 0; const centerY = 200; const range = 50; const speed = 0.05; ball.x = canvas.width / 2; // 堆代码 duidaima.com const drawFrame = () => { Utils.requestAnimationFrame()(drawFrame); context.clearRect(0, 0, canvas.width, canvas.height); ball.y = centerY + Math.sin(angle) * range; angle += speed; ball.draw(context); }; drawFrame(); };centerY:小球在画布中的初始垂直中心位置。在代码中是 200,表示在画布的垂直中间。
speed:控制每一帧增加的角度,值越大,小球上下摆动的速度越快。
window.onload = () => { const canvas = document.getElementById('canvas'); const context = canvas.getContext('2d'); const ball = new Ball(); let angle = 0; const centerY = 200; const range = 50; const xspeed = 1; const yspeed = 0.05; ball.x = 0; const drawFrame = () => { Utils.requestAnimationFrame()(drawFrame); context.clearRect(0, 0, canvas.width, canvas.height); ball.x += xspeed; ball.y = centerY + Math.sin(angle) * range; angle += yspeed; ball.draw(context); }; drawFrame(); };这段代码让小球不仅在Y轴上摆动,还会沿着X轴前进,最终形成一个波浪前进的动画效果。