canvas中的三角运动(3) —— 正弦波运动
Rod8448
8年前
<h2>一. 需求:</h2> <p>要求:让小球沿着正弦波运动。</p> <p>小球的构造函数如下:</p> <pre> <code class="language-java">// 圆球的构造函数 function Ball(radius, color) { if(radius === undefined) { radius = 40; } if(color === undefined) { color = "#ff0000"; } this.x = 0; this.y = 0; this.radius = radius; this.rotation = 0; this.scaleX = 1; this.scaleY = 1; this.color = color; this.lineWidth = 1; } Ball.prototype.draw = function(context) { context.save(); context.translate(this.x, this.y); context.rotate(this.rotation); context.scale(this.scaleX, this.scaleY); context.lineWidth = this.lineWidth; context.fillStyle = this.color; context.beginPath(); context.arc(0, 0, this.radius, 0, Math.PI * 2, true); context.closePath(); context.fill(); if(this.lineWidth > 0) { context.stroke(); } context.restore(); }</code></pre> <h2>二. 思路分析:</h2> <p>正弦波的实现可以使用正弦函数 Math.sin(angle) 绘制。其中, angle值作为变量并递增时,即可使物体按正弦曲线运动,从而实现正弦波动画 。</p> <p><img src="https://simg.open-open.com/show/6798f2c74d656105f06612e4faff3cd2.png"></p> <p>过程如下:</p> <pre> <code class="language-java">(function drawFrame() { window.requestAnimationFrame(drawFrame, canvas); ball.y = Math.sin(angle) * range; angle += speed; ball.draw(context); })();</code></pre> <p>可以在控制台中输出以下代码,了解下正弦波的数值分布:</p> <pre> <code class="language-java">var fullRadians = Math.PI * 2; for(var angle = 0; angle < fullRadians; angle += 0.01) { console.log(Math.sin(angle)); }</code></pre> <h2>三. 实例:</h2> <p>代码:</p> <pre> <code class="language-java"><canvas id="canvas" width="400" height="400" style="background: #ccc;"></canvas> window.onload = function() { var canvas = document.getElementById("canvas"), context = canvas.getContext("2d"), ball = new Ball(2), angle = 0, range = 50, speed = 0.1, isFoward = true; ball.x = 0; ball.y = canvas.height / 2; ball.lineWidth = 0; (function drawFrame() { window.requestAnimationFrame(drawFrame, canvas); // context.clearRect(0, 0, canvas.width, canvas.height); ball.y = canvas.height / 2 + Math.sin(angle) * 100; if(isFoward) { ball.x += speed * 20; } else { ball.x -= speed * 20; } if(ball.x > canvas.width) { isFoward = false; context.clearRect(0, 0, canvas.width, canvas.height); } else if(ball.x < 0) { isFoward = true; context.clearRect(0, 0, canvas.width, canvas.height); } angle += speed; ball.draw(context); })(); };</code></pre> <p>演示如下: <a href="/misc/goto?guid=4959677070754610126" rel="nofollow,noindex">http://codepen.io/dengzhirong/pen/xOZypy</a></p> <h2>四. 总结:</h2> <p>创建正弦波的方法,就是使用正弦函数 Math.sin(angle) 求值,并让弧度值angle根据运动时间递增。</p> <p>创建正弦波的公式如下:</p> <pre> <code class="language-java">/** * range:正选的波峰值 * center:y轴的交点 * speed:正弦波的运动速度 * angle:弧度值,递增的变量 */ (function drawFrame() { window.requestAnimationFrame(drawFrame, canvas); valeue = center + Math.sin(angle) * range; angle += speed; })();</code></pre> <p> </p> <p>来自:http://www.dengzhr.com/js/956</p> <p> </p> <p><span style="color:rgb(255, 255, 255)">Save</span></p>